Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

The shortest part to sort so the whole array is sorted

Medium · Target 15 minutes · Two pointers· Type asked at

You're given an integer array nums. Find the shortest continuous subarray that, if you sorted just that part in ascending order, would leave the whole array sorted, and return its length. If the array's sorted already the answer's 0.

Examples

InputOutputWhy
nums = [2, 6, 4, 8, 10, 9, 15]5You'd sort 6, 4, 8, 10, 9 and I think you'll find everything else is already where it should be.
nums = [1, 2, 3, 4]0
nums = [1, 3, 2, 2, 2]4The 3 has to end up behind all three 2's, so the part to sort runs from the 3 to the end.

Constraints

  • 1 ≤ n ≤ 10⁴
  • −10⁵ ≤ nums[i] ≤ 10⁵

Hints

Hint 1

Sorting a copy and comparing the two works in O(n log n), but do you think you could say where the part to sort has to end without sorting anything at all?

Hint 2

I'd walk left to right and keep the biggest value you've seen so far. Any element that's smaller than that maximum is out of place, which means the part you sort has to reach at least that far.

Hint 3

The last element like that is your right end. If you do the same thing from the right with the running minimum, the last element that's bigger than it gives you the left end.

Where people lose marks

  • Taking the first place where nums[i] > nums[i + 1] as the left end. In 1, 3, 5, 4, 2 the first drop is at the 5, but the 2 at the end has to go in front of the 3, so the part to sort starts at the 3.
  • Comparing with ≤ in place of <, when an equal value next to the maximum is probably fine where it is and counting it would stretch the answer for no reason.
  • Forgetting about the array that's sorted already. If neither pass finds anything the answer's 0, and it's quite easy to get that wrong by working out right − left + 1 anyway.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.