Skip to content

Update 2.10-minimum-window-sort-medium.md #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 77 additions & 1 deletion 2.-pattern-two-pointers/2.10-minimum-window-sort-medium.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,78 @@
# 2.10 Minimum Window Sort \(medium\)
Given an array, find the length of the smallest subarray that, when sorted, results in the entire array being sorted.

📥 Examples
Example 1
Input: [1, 3, 2, 0, -1, 7, 10]
Output: 5
Explanation: The subarray [3, 2, 0, -1, 7] must be sorted to sort the entire array.

Example 2
Input: [1, 2, 5, 3, 7, 10, 9, 12]
Output: 5
Explanation: The subarray [5, 3, 7, 10, 9] must be sorted.

💡 Approach: Sliding Window Strategy
We need to:

Find the first element out of order from the start.

Find the first element out of order from the end.

Determine the minimum and maximum of the subarray between them.

Expand the window left/right if the min/max affect the elements outside.

Return the length of this window.

🧠 Java Code
java
Copy
Edit
public int shortestWindowToSort(int[] arr) {
int low = 0, high = arr.length - 1;

// Step 1: Move 'low' forward while array is sorted
while (low < arr.length - 1 && arr[low] <= arr[low + 1]) {
low++;
}

// Array is already sorted
if (low == arr.length - 1) return 0;

// Step 2: Move 'high' backward while array is sorted
while (high > 0 && arr[high] >= arr[high - 1]) {
high--;
}

// Step 3: Find min and max in the subarray
int subarrayMin = Integer.MAX_VALUE;
int subarrayMax = Integer.MIN_VALUE;
for (int k = low; k <= high; k++) {
subarrayMin = Math.min(subarrayMin, arr[k]);
subarrayMax = Math.max(subarrayMax, arr[k]);
}

// Step 4: Expand window to the left
while (low > 0 && arr[low - 1] > subarrayMin) {
low--;
}

// Step 5: Expand window to the right
while (high < arr.length - 1 && arr[high + 1] < subarrayMax) {
high++;
}

return high - low + 1;
}
⏱ Time Complexity
O(N) — Only a few linear scans through the array.

💾 Space Complexity
O(1) — Constant space, no extra data structures used.

✅ Summary
We don’t sort the array; we find the part that needs sorting.

Expand the range if sorting the subarray still doesn’t fix the full array.

Efficient and clean solution — great for interviews and real-world use.