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] <= 100numsis sorted in non-decreasing order
Approach
Two Pointers pattern
1. Handle Empty Array
- If
nums.length === 0, return0 - 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
jstarts at1(fast pointer, scans through the array)
3. Scan With the Fast Pointer
- Iterate
jfrom1tonums.length - 1 - For each element
nums[j], compare it tonums[i]
4. Place Unique Elements
- If
nums[j] !== nums[i]: - Increment
i - Copy
nums[j]intonums[i] - This overwrites duplicate positions with the next unique value
5. Return the Count
- After the loop,
iis the index of the last unique element - Return
i + 1as the total number of unique elements
🧠 Key Insight
- Because the array is already sorted, all duplicates are adjacent
- The slow pointer
ionly advances when a new unique value is found - The fast pointer
jskips over duplicates naturally
Time
O(n)single pass through the arraySpace
O(1)in-place modification, no extra storageVisualization
Input:
[1, 1, 2]
—
Press ▶ or use ← → to step through
Pointer iPointer jProcessedDone
5 steps