Categories: Data Structure

DSA: SubArray

What is a SubArray?

  • A subarray is a sequence of elements within an array that is contiguous. In other words, a subarray is a section of an array that contains consecutive elements in the same sequence as the original array.
  • Subarrays can range in length from a single element (also considered a subarray) to the full array. If we have an array [1, 2, 3, 4], some of its subarrays are  [1], [2, 3], [4], [1, 2, 3, 4], etc.
  • Subarrays are a commonly used concept in computer science and algorithms. Many problems involving arrays and sequences can be solved using subarray manipulation techniques.
Example:

Let us take a look at a few example to understand the subarray concept.

Question 1:

1. You are given an array of size ‘n’ and n elements of the same array.
2. You must find and print all the subarrays of the given array.
3. Each subarray should be space seperated and on a seperate lines. Refer to sample input and output.

import java.io.*;
import java.util.*;

public class Main{

public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int[] arr = new int[n];

    for(int i = 0; i < n; i++){
       arr[i] = Integer.parseInt(br.readLine());
    }

    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < arr.length; i++){
       for(int j = i; j < arr.length; j++){
          for(int k = i; k <= j; k++){
            sb.append(arr[k] + "\t");
          }
          sb.append("\n");
       }
    }

    System.out.println(sb);
 }}

Output:

5
1
 2
 3
 4
 5

output:
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
2 
2 3 
2 3 4 
2 3 4 5 
3 
3 4 
3 4 5 
4 
4 5 
5

This Java code reads from the user an integer n, which represents the size of an array. The programme then reads n integers from the user and populates an array arr with these values. The code then generates all possible arr subarrays and outputs them to the console in tab-separated format, with each subarray on a new line.

Question 2:

Given two integer values N and K, the task is to create an array A of N integers such that number of the total positive sum subarrays is exactly K and the remaining subarrays have a negative sum .

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int N = 5; // size of the array
        int K = 3; // required number of positive sum subarrays

        int[] A = new int[N];
        Arrays.fill(A, -1); // initialize the array with -1

        int positiveSumCount = 0;

        for (int i = 0; i < N; i++) {
            if (positiveSumCount < K) {
                A[i] = 1;
                positiveSumCount++;
            }
        }

        if (positiveSumCount < K) {
            for (int i = 0; i < N; i++) {
                if (A[i] == -1) {
                    A[i] = 1;
                    positiveSumCount++;
                }

                if (positiveSumCount == K) {
                    break;
                }
            }
        }

        if (positiveSumCount > K) {
            for (int i = 0; i < N; i++) {
                if (A[i] == -1) {
                    A[i] = -1;
                    positiveSumCount--;
                }

                if (positiveSumCount == K) {
                    break;
                }
            }
        }

        System.out.println("Array A: " + Arrays.toString(A));
    }
}

The above code:

  1. Create an array A of size N with all elements initialized to -1.
  2. Initialize a variable positiveSumCount to 0 to keep track of the number of positive sum subarrays.
  3. Iterate through the array A from left to right.
  4. For each element A[i], check if positiveSumCount is less than K. If it is, set A[i] to 1 and increment positiveSumCount.
  5. If positiveSumCount is equal to K, set the remaining elements of A to -1.
  6. If after setting all remaining elements to -1, positiveSumCount is still less than K, set the remaining elements to 1 to create negative sum subarrays.
  7. If after setting all remaining elements to 1, positiveSumCount is still greater than K, set the remaining elements to -1 to create negative sum subarrays.

Note: also read about Array Carry Forward

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago