Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Allow each value at most twice in a sorted array (in place) and return the new length.
Problem: Allow each value at most twice in a sorted array (in place) and return the new length.
def keep2(a):
w = 0
for x in a:
if w < 2 or x != a[w - 2]:
a[w] = x
w += 1
return w
print(keep2([0, 0, 0, 1, 1, 1, 1, 2, 3, 3]))What is returned?- A. 5
- B. 8
- C. 4
- D. 7
Correct answer: D. 7
Compare each value with the element two places behind the WRITE pointer: kept values are 0, 0, 1, 1, 2, 3, 3 → 7. Comparing with a[w − 1] lets only the first value keep two copies (5), allowing w ≤ 2 unconditionally admits a third 0 (8), and keeping one copy of each value gives 4. O(n), O(1) space.
More Coding Interview Problems questions
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…
- Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable. python def longestones(a, k): l =…