‹ DS&A interview · Socratic
DSA · Arrays & Two Pointers · #142

Remove Duplicates from Sorted Array II

Module 40 · difficulty 3/5·30:00starts on first keystroke

Given an integer array `nums` sorted in **non-decreasing** order, remove duplicates **in-place** so that each unique element appears **at most twice**. The relative order of the elements must be kept the same. Do this by modifying `nums` in-place. Return `k`, the number of kept elements; the first `k` slots of `nums` must hold the result and the rest don't matter. Implement `function removeDuplicates(nums)` which returns the integer `k`.

Examples
  • nums = [1,1,1,2,2,3] 5, nums = [1,1,2,2,3,_]Keep two 1s, two 2s, one 3.
  • nums = [0,0,1,1,1,1,2,3,3] 7, nums = [0,0,1,1,2,3,3,_,_]Each value appears at most twice in the prefix.
  • nums = [1,2,3] 3, nums = [1,2,3]No duplicates to trim.
Constraints
  • · 1 <= nums.length <= 3 * 10^4
  • · -10^4 <= nums[i] <= 10^4
  • · nums is sorted in non-decreasing order
  • · Must run in O(1) extra space
  • · Only the first k elements are checked
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.