Back to Dashboard
Minimum Window Sort
MediumProblem Statement
Given an array, find the length of the smallest subarray in it which when sorted will sort the whole array.
Examples
Example 1:
- Input:
nums = [1, 2, 5, 3, 7, 10, 9, 12] - Output:
5 - Explanation: Explanation: We need to sort only the subarray
[5, 3, 7, 10, 9]to make the whole array sorted
Approach 1: Two Pointers
O(n)
O(1)
class Solution {
public int findUnsortedSubarray(int[] nums) {
var low = 0;
var high = nums.length - 1;
while (low < nums.length - 1) {
if (nums[low] > nums[low + 1]) {
break;
}
low ++;
}
if (low == nums.length - 1) {
return 0;
}
while (high > 0) {
if (nums[high] < nums[high - 1]) {
break;
}
high --;
}
var windowMax = Integer.MIN_VALUE;
var windowMin = Integer.MAX_VALUE;
for (int i = low; i <= high; i ++) {
windowMax = Math.max(windowMax, nums[i]);
windowMin = Math.min(windowMin, nums[i]);
}
var left = 0;
for (int i = 0; i <= low; i ++) {
if (windowMin < nums[i]) {
left = i;
break;
}
}
var right = nums.length - 1;
for (int i = nums.length - 1; i >=0; i --) {
if (windowMax > nums[i]) {
right = i;
break;
}
}
return right - left + 1;
}
}