703869. Shortest un-ordered subarray

Basic

Shortest Un-Ordered Subarray

Summary

The problem is to find the shortest subarray within a given array that has all elements in an un-ordered manner. This means that if we consider all possible orderings of the elements, the subarray should be the one with the minimum length among all such orderings.

Detailed Explanation

To solve this problem, we can start by iterating through the array and considering each element as a potential starting point for our shortest un-ordered subarray. For each element, we then need to find the longest suffix that contains all elements in some arbitrary order. This is because if we have found such a suffix, it means that any prefix of this suffix would also be a valid un-ordered subarray.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers start and end to 0.
  2. Iterate through the array starting from the current element at index i.
  3. For each element, initialize a set unordered_elements to store all unique elements in the subarray.
  4. Initialize a variable max_length to 0 to keep track of the maximum length of an un-ordered subarray found so far.
  5. Iterate through the array from index start to i (inclusive) and add each element to the set unordered_elements.
  6. Check if the size of unordered_elements is equal to the number of unique elements in the subarray. If it's not, then we have found an un-ordered subarray.
  7. Update max_length with the maximum length found so far.
  8. Repeat steps 2-7 for all elements in the array.

Time complexity: O(n^2) where n is the size of the array. This is because for each element, we are potentially iterating through the entire array to check if it's an un-ordered subarray. Space complexity: O(1) as we only need a constant amount of space to store our variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int shortestUnorderedSubarray(int[] arr) {
    int n = arr.length;
    int max_length = 0;
    for (int i = 0; i < n; i++) {
        Set<Integer> unordered_elements = new HashSet<>();
        for (int j = start; j <= i; j++) {
            unordered_elements.add(arr[j]);
        }
        if (unordered_elements.size() == arr.length) {
            max_length = Math.max(max_length, i - start + 1);
        }
    }
    return max_length;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.