Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted.

Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted.
def shortest_unsorted(a):
    n = len(a); end, start = -1, 0
    mx, mn = a[0], a[-1]
    for i in range(n):
        mx = max(mx, a[i])
        if a[i] < mx: end = i
        mn = min(mn, a[n - 1 - i])
        if a[n - 1 - i] > mn: start = n - 1 - i
    return end - start + 1
print(shortest_unsorted([2, 6, 4, 8, 10, 9, 15]), shortest_unsorted([1, 2, 3, 4]), shortest_unsorted([1, 3, 2, 2, 2]))
What is printed?
  1. A. 5 0 4
  2. B. 5 0 2
  3. C. 4 0 4
  4. D. 5 1 4

Correct answer: A. 5 0 4

Scanning left to right, any element smaller than the running max must be inside the window (last such index = end); scanning right to left, any element larger than the running min marks start. [2, 6, 4, 8, 10, 9, 15] → indices 1..5 = 5. A sorted array gives end = −1, start = 0 → 0. [1, 3, 2, 2, 2] → indices 1..4 = 4 (all the 2s must move). O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic