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?
  1. A. 5
  2. B. 8
  3. C. 4
  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

Exams that ask this topic