Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

Keep each value at most twice

Medium · Target 15 minutes · Two pointers

Given an integer array nums sorted in non-decreasing order, remove extra copies in place so that each value appears at most twice, keeping the order. Use O(1) extra memory. Return the kept prefix of the array.

Examples

InputOutputWhy
nums = [1, 1, 1, 2, 2, 3][1, 1, 2, 2, 3]
nums = [0, 0, 1, 1, 1, 1, 2, 3, 3][0, 0, 1, 1, 2, 3, 3]

Constraints

  • 1 ≤ n ≤ 3 × 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums is sorted in non-decreasing order

Hints

Hint 1

With "at most once", you write a value when it differs from the last value written. What changes for "at most twice"?

Hint 2

Copies of a value are next to each other. A third copy is exactly a value equal to the one written two places earlier.

Hint 3

Keep a write index w. Write nums[r] at w when w < 2 or nums[r] differs from nums[w − 2].

Where people lose marks

  • Comparing with nums[r − 2] instead of nums[w − 2]. The reader's neighbours may already have been dropped; only the kept prefix tells you how many copies are kept.
  • Counting copies with a separate counter that is not reset when the value changes.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.