Sub array java – Java Program to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers

Sub array java: In the previous article, we have seen Java Program to Separate all Even Numbers First and Then Odd Number

In this article we are going to see how to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers using Java Programming Language.

Java Program to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers.

Method-1: Java Program to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers By Static Initialization of Array Elements

Approach:

  • Initialize the variables len = 1, start = 0, end = 0.
  • Create a for loop from i= 0 -> arr.length -1 and another j = i+1 -> arr.length.
  • Find min and max from the array.
  • Check if the array is consecutive
  • Check if difference between max and min is equal to the difference between the start and end indices.
  • Create a visited array and check if any element is present more than once, return false.
  • If the subarray is consecutive, update len = max-min + 1, and indices start = I and end = j.
  • Print the subarray.

Program:

import java.util.Arrays;

public class Main
{

    public static void main(String[] args) {
        // initialize the array
        int[] arr = { 2, 5, 0, 2, 1, 4, 3, 6, 1, 0 };
        // call the method
        checkConsecutiveSubarray(arr);
    }

    static boolean is_consecutive(int nums[], int start, int end, int min, int max) {
        // for the subarray to be consecutive, the difference between
        // max and min must be equal to the difference between end and start index
        if (max - min != end - start) {
            return false;
        }
        // initialize the visited array
        boolean check[] = new boolean[end - start + 1];
        // if an element is already visited, return false
        for (int i = start; i <= end; i++) {
            if (check[nums[i] - min]) {
                return false;
            }

            check[nums[i] - min] = true;
        }
        // if we manage to reach here, it means the subarray is consecutive
        return true;
    }

    public static void checkConsecutiveSubarray(int[] arr) {
        int len = 1;
        int start = 0, end = 0;

        for (int i = 0; i < arr.length - 1; i++) {
            int min_val = arr[i], max_val = arr[i];

            for (int j = i + 1; j < arr.length; j++) {
                // get min and max values of the subarray
                min_val = Math.min(min_val, arr[j]);
                max_val = Math.max(max_val, arr[j]);
                // if the subarray is consecutive, update the length, start and end indices
                if (is_consecutive(arr, i, j, min_val, max_val)) {
                    if (len < max_val - min_val + 1) {
                        len = max_val - min_val + 1;
                        start = i;
                        end = j;
                    }
                }
            }
        }

        System.out.println("The largest subarray is " + Arrays.toString(Arrays.copyOfRange(arr, start, end + 1))
                + " of length " + len);
    }

}

Output:

The largest subarray is [5, 0, 2, 1, 4, 3, 6] of length 7

Method-2: Java Program to Check if a Sub Array is Formed by Consecutive Integers from a Given Array of Integers By Dynamic Initialization of Array Elements

Approach:

  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Initialize the variables len = 1, start = 0, end = 0.
  • Create a for loop from i= 0 -> arr.length -1 and another j = i+1 -> arr.length.
  • Find min and max from the array.
  • Check if the array is consecutive
  • Check if difference between max and min is equal to the difference between the start and end indices.
  • Create a visited array and check if any element is present more than once, return false.
  • If the subarray is consecutive, update len = max-min + 1, and indices start = I and end = j.
  • Print the subarray.

Programs:

import java.util.Arrays;
import java.util.Scanner;

public class LargestConsSubArray_64 {

    public static void main(String[] args) {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.println("Enter array elements: ");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        // call the method
        checkConsecutiveSubarray(arr);
    }

    static boolean is_consecutive(int nums[], int start, int end, int min, int max) {
        // for the subarray to be consecutive, the difference between
        // max and min must be equal to the difference between end and start index
        if (max - min != end - start) {
            return false;
        }
        // initialize the visited array
        boolean check[] = new boolean[end - start + 1];
        // if an element is already visited, return false
        for (int i = start; i <= end; i++) {
            if (check[nums[i] - min]) {
                return false;
            }

            check[nums[i] - min] = true;
        }
        // if we manage to reach here, it means the subarray is consecutive
        return true;
    }

    public static void checkConsecutiveSubarray(int[] arr) {
        int len = 1;
        int start = 0, end = 0;

        for (int i = 0; i < arr.length - 1; i++) {
            int min_val = arr[i], max_val = arr[i];

            for (int j = i + 1; j < arr.length; j++) {
                // get min and max values of the subarray
                min_val = Math.min(min_val, arr[j]);
                max_val = Math.max(max_val, arr[j]);
                // if the subarray is consecutive, update the length, start and end indices
                if (is_consecutive(arr, i, j, min_val, max_val)) {
                    if (len < max_val - min_val + 1) {
                        len = max_val - min_val + 1;
                        start = i;
                        end = j;
                    }
                }
            }
        }

        System.out.println("The largest subarray is " + Arrays.toString(Arrays.copyOfRange(arr, start, end + 1))
                + " of length " + len);
    }

}

Output:

Enter the size of array: 9
Enter array elements: 1 2 3 4 5 6 7 8 9
The largest subarray is [1, 2, 3, 4, 5, 6, 7, 8, 9] of length 9

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: