Friday, September 5, 2025
HomeLanguagesPython3 Program for Shortest Un-ordered Subarray

Python3 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.
 

Python3




# Python3 program to find shortest
# subarray which is unsorted
 
# Bool function for checking an array 
# elements are in increasing
def increasing(a, n):
 
    for i in range(0, n - 1):
        if (a[i] >= a[i + 1]):
            return False
             
    return True
 
# Bool function for checking an array
# elements are in decreasing
def decreasing(a, n):
 
    for i in range(0, n - 1):
        if (a[i] < a[i + 1]):
            return False
             
    return True
 
def shortestUnsorted(a, n):
 
    # increasing and decreasing are two functions.
    # if function return True value then print
    # 0 otherwise 3.
    if (increasing(a, n) == True or
        decreasing(a, n) == True):
        return 0
    else:
        return 3
 
# Driver code
ar = [7, 9, 10, 8, 11]
n = len(ar)
print(shortestUnsorted(ar, n))
 
# This code is contributed by Smitha Dinesh Semwal.


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS