1. Check All Subarrays (Brute Force)
Intuition
Iterate through all pairs (i, j) with 0 <= i <= j < n. For each pair, create a copy of nums, sort the segment from i to j, and check if the entire array is sorted. The smallest difference j - i + 1 among all valid pairs is the answer.
When to apply: Use to understand the minimal contiguous unsorted window definition.
Brute Force Window Validation Trace
2 of 2 questions left todayArray: [2, 6, 4, 8, 10, 9, 15]
Array: [2, 6, 4, 8, 10, 9, 15]. Full length n = 7.
public class Main { public static class Solution { public int findUnsortedSubarray(int[] nums) { int n = nums.length; int minLen = n; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int[] copy = nums.clone(); java.util.Arrays.sort(copy, i, j + 1); if (isSorted(copy)) { minLen = Math.min(minLen, j - i + 1); } } } return isSorted(nums) ? 0 : minLen; } private boolean isSorted(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[i + 1]) return false; } return true; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {2, 6, 4, 8, 10, 9, 15}; System.out.println("Shortest Unsorted Subarray: " + sol.findUnsortedSubarray(nums)); }}Time & Space Complexity
- Time complexity:
O(n^3)— O(n2) pairs, each requiring an O(n log n) or O(n) validation. - Space complexity:
O(n)— O(n) memory to store the copied array for verification.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.