Saturday, December 6, 2025
HomeLanguagesJavaJava Program for Shortest Un-ordered Subarray

Java Program for Shortest Un-ordered Subarray

An array is given of n length, and problem is that we have to find the length of shortest unordered {neither increasing nor decreasing} sub array in given array.
Examples: 
 

Input : n = 5
        7 9 10 8 11
Output : 3
Explanation : 9 10 8 unordered sub array.

Input : n = 5
       1 2 3 4 5
Output : 0 
Explanation :  Array is in increasing order.

 

The idea is based on the fact that size of shortest subarray would be either 0 or 3. We have to check array element is either increasing or decreasing, if all array elements are in increasing or decreasing, then length of shortest sub array is 0, And if either the array element is not follow the increasing or decreasing then it shortest length is 3.
 

Java




// JAVA program to find shortest subarray which is
// unsorted.
import java.util.*;
import java.io.*;
 
class GFG {
     
    // boolean function to check array elements
    // are in increasing order or not
    public static boolean increasing(int a[],int n)
    {
        for (int i = 0; i < n - 1; i++)
            if (a[i] >= a[i + 1])
                return false;
                 
        return true;
    }
     
    // boolean function to check array elements
    // are in decreasing order or not
    public static boolean decreasing(int arr[],int n)
    {
        for (int i = 0; i < n - 1; i++)
            if (arr[i] < arr[i + 1])
                return false;
                 
        return true;
    }
     
    public static int shortestUnsorted(int a[],int n)
    {
         
        // increasing and decreasing are two functions.
        // if function return true value then print
        // 0 otherwise 3.
        if (increasing(a, n) == true ||
                             decreasing(a, n) == true)
            return 0;
        else
            return 3;
    }
     
    // driver program
    public static void main (String[] args) {
         
        int ar[] = new int[]{7, 9, 10, 8, 11};
        int n = ar.length;
         
        System.out.println(shortestUnsorted(ar,n));
    }
}
 
// This code is contributed by Akash Singh.


Output : 

3

 

Time complexity: O(n) where n is the length of the array.

Auxiliary Space: O(1)

Please refer complete article on Shortest Un-ordered Subarray for more details!

RELATED ARTICLES

Most Popular

Dominic
32427 POSTS0 COMMENTS
Milvus
98 POSTS0 COMMENTS
Nango Kala
6802 POSTS0 COMMENTS
Nicole Veronica
11944 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12012 POSTS0 COMMENTS
Shaida Kate Naidoo
6932 POSTS0 COMMENTS
Ted Musemwa
7185 POSTS0 COMMENTS
Thapelo Manthata
6881 POSTS0 COMMENTS
Umr Jansen
6867 POSTS0 COMMENTS