Coding Interview PatternsRemove Duplicates from Sorted Array
EasyTwo Pointers

Remove Duplicates from Sorted Array

Explanation & Solution

Description

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements.

More formally, if there are k unique elements, the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Input:nums = [1, 1, 2]
0
1
1
1
2
2

Output: 2

Explanation: The function returns k = 2, with the first two elements of nums being [1, 2].

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order

Approach

Two Pointers pattern

1. Handle Empty Array

  • If nums.length === 0, return 0
  • There are no elements, so zero unique values

2. Initialize Two Pointers

  • Set i = 0 (slow pointer, tracks the position of the last unique element)
  • The loop variable j starts at 1 (fast pointer, scans through the array)

3. Scan With the Fast Pointer

  • Iterate j from 1 to nums.length - 1
  • For each element nums[j], compare it to nums[i]

4. Place Unique Elements

  • If nums[j] !== nums[i]:
  • Increment i
  • Copy nums[j] into nums[i]
  • This overwrites duplicate positions with the next unique value

5. Return the Count

  • After the loop, i is the index of the last unique element
  • Return i + 1 as the total number of unique elements

🧠 Key Insight

  • Because the array is already sorted, all duplicates are adjacent
  • The slow pointer i only advances when a new unique value is found
  • The fast pointer j skips over duplicates naturally
Time
O(n)single pass through the array
Space
O(1)in-place modification, no extra storage

Visualization

Input:
[1, 1, 2]
101122

Press ▶ or use ← → to step through

Pointer iPointer jProcessedDone
5 steps

Solution Code