← Questions

Shortest unsorted continuous subarray

0
AmazonCodingLast asked Aug 2025

A coding interview question asked in Amazon's technical phone screen, last asked Aug 2025. It tests arrays, two pointers and sorting.

Given an integer array, find the shortest contiguous subarray that, once sorted in ascending order, leaves the whole array sorted in non-decreasing order. Return its length, or 0 if the array is already sorted.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • shortest_unsorted(nums: list[int]) -> int

Example

shortest_unsorted([2, 6, 4, 8, 10, 9, 15])  ->  5   # sort [6, 4, 8, 10, 9]
shortest_unsorted([1, 2, 3, 4])             ->  0
shortest_unsorted([1, 3, 2, 2, 2])          ->  4   # sort [3, 2, 2, 2]
shortest_unsorted([5, 4, 3, 2, 1])          ->  5

Constraints

  • 0 <= len(nums) <= 10^4; -10^5 <= nums[i] <= 10^5.
  • Duplicates are allowed; the result must be non-decreasing, not strictly increasing.

Clarifying questions

  • Is the target order non-decreasing (duplicates allowed) or strictly increasing?
  • What should an empty or one-element array return?
  • Do you want the length only, or also the start and end indices?

What a strong answer covers

  • Brute force first, then sorting a copy and comparing: the first and last positions that differ bound the answer, O(n log n).
  • The O(n) two-scan solution: left to right with a running maximum, the last index smaller than that maximum is the right edge; right to left with a running minimum, the last index larger than that minimum is the left edge.
  • Why the scans are correct, and why a single dip is not enough ([1, 3, 2, 2, 2] must extend over all the 2s).
  • Edge cases: already sorted, strictly decreasing, all equal, duplicates at the edges of the window.

Follow-ups

  • Return the indices of the window.
  • Solve it in one pass with O(1) extra space.
  • The array arrives as a stream: keep the answer up to date after each new element.

Where it's asked

  • Amazon · Technical phone screen · Last asked Aug 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

arrays · two pointers · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding