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?- A. 5 0 4
- B. 5 0 2
- C. 4 0 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
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…
- Problem: Given n ≤ 10⁵ words, find the longest chain where each word is the previous word with exactly one letter inserted (word length ≤…
- Problem: A string of length n = 10⁵; answer q = 10⁵ queries 'are substrings [l1, r1] and [l2, r2] equal?'. Which technique fits?
- Problem: n ≤ 40 items with weights up to 10⁹; count subsets with total weight ≤ W. Why is meet-in-the-middle preferred here?