Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.
Return the shortest such subarray and output its length.
Example 1:
Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Example 2:
Input: nums = [1,2,3,4] Output: 0
Example 3:
Input: nums = [1] Output: 0
Constraints:
1 <= nums.length <= 104-105 <= nums[i] <= 105O(n) time complexity?Problem summary: Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order. Return the shortest such subarray and output its length.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Stack · Greedy
[2,6,4,8,10,9,15]
[1,2,3,4]
[1]
smallest-subarray-to-sort-in-every-sliding-window)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #581: Shortest Unsorted Continuous Subarray
class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] arr = nums.clone();
Arrays.sort(arr);
int l = 0, r = arr.length - 1;
while (l <= r && nums[l] == arr[l]) {
l++;
}
while (l <= r && nums[r] == arr[r]) {
r--;
}
return r - l + 1;
}
}
// Accepted solution for LeetCode #581: Shortest Unsorted Continuous Subarray
func findUnsortedSubarray(nums []int) int {
arr := make([]int, len(nums))
copy(arr, nums)
sort.Ints(arr)
l, r := 0, len(arr)-1
for l <= r && nums[l] == arr[l] {
l++
}
for l <= r && nums[r] == arr[r] {
r--
}
return r - l + 1
}
# Accepted solution for LeetCode #581: Shortest Unsorted Continuous Subarray
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
arr = sorted(nums)
l, r = 0, len(nums) - 1
while l <= r and nums[l] == arr[l]:
l += 1
while l <= r and nums[r] == arr[r]:
r -= 1
return r - l + 1
// Accepted solution for LeetCode #581: Shortest Unsorted Continuous Subarray
impl Solution {
pub fn find_unsorted_subarray(nums: Vec<i32>) -> i32 {
let mut arr = nums.clone();
arr.sort();
let mut l = 0usize;
while l < nums.len() && nums[l] == arr[l] {
l += 1;
}
if l == nums.len() {
return 0;
}
let mut r = nums.len() - 1;
while r > l && nums[r] == arr[r] {
r -= 1;
}
(r - l + 1) as i32
}
}
// Accepted solution for LeetCode #581: Shortest Unsorted Continuous Subarray
function findUnsortedSubarray(nums: number[]): number {
const arr = [...nums];
arr.sort((a, b) => a - b);
let [l, r] = [0, arr.length - 1];
while (l <= r && arr[l] === nums[l]) {
++l;
}
while (l <= r && arr[r] === nums[r]) {
--r;
}
return r - l + 1;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.