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

Remove Duplicates from Sorted Array

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

Given an integer array `nums` sorted in non-decreasing order, remove the duplicates **in-place** so that each unique element appears only once. The relative order of the elements must be kept the same. Return `k`, the number of unique elements. The first `k` slots of `nums` must hold the unique values in their original order; whatever is left beyond index `k` does not matter. Implement `removeDuplicates(nums)`, which mutates `nums` in place and returns the integer `k`.

Examples
  • nums = [1, 1, 2] 2nums becomes [1, 2, _]. The first 2 elements are the unique values.
  • nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] 5nums becomes [0, 1, 2, 3, 4, ...].
  • nums = [] 0An empty array has zero unique elements.
Constraints
  • · 0 <= nums.length <= 3 * 10^4
  • · -100 <= nums[i] <= 100
  • · nums is sorted in non-decreasing order
  • · Must run in O(1) extra space (modify in place)
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.