Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each value just above its predecessor).
Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each value just above its predecessor).
def min_incr(a):
a = sorted(a); moves = 0
for i in range(1, len(a)):
if a[i] <= a[i - 1]:
moves += a[i - 1] + 1 - a[i]
a[i] = a[i - 1] + 1
return moves
print(min_incr([4, 1, 4, 2, 2, 9]), min_incr([6, 6, 6]))What is printed?- A. 3 3
- B. 4 3
- C. 2 2
- D. 2 3
Correct answer: D. 2 3
After sorting, the cheapest distinct assignment keeps the order and raises each value to max(itself, previous + 1). [1, 2, 2, 4, 4, 9] → [1, 2, 3, 4, 5, 9]: 1 + 1 = 2 moves. [6, 6, 6] → [6, 7, 8]: 0 + 1 + 2 = 3. Counting duplicates (2 here) only works when the next value up happens to be free. O(n log n).
More Coding Interview Problems questions
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…
- Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums…