Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

Array [1, 3, 5, 4, 2, 6, 8, 7, 9]. What is the length of the shortest contiguous segment that, once sorted, makes the whole array sorted?

  1. A. 7
  2. B. 5
  3. C. 4
  4. D. 9

Correct answer: A. 7

Scan for the leftmost index where a value exceeds a later minimum (index 1, value 3 > 2) and the rightmost where a value is below an earlier maximum (index 7, value 7 < 8): the segment 1..7 has length 7. Counting only the misplaced positions (1, 2, 4, 6, 7) gives 5, fixing just the first dip [3, 5, 4, 2] gives 4, and 9 sorts the whole array.

More Coding Interview Problems questions

Exams that ask this topic