26. Remove Duplicates from Sorted Array
At a Glance
- Topic: arrays-hashing
- Pattern: Two Pointers
- Difficulty: Easy
- Companies: Amazon, Google, Meta, Microsoft, Bloomberg
- Frequency: High
- LeetCode: 26
Problem (one-liner)
Given sorted integers numbers, remove duplicates in-place so each unique value appears once. Return uniqueCount; first uniqueCount slots contain sorted unique values in order.
Recognition Cues
- "Sorted array", "remove duplicates in-place"
- Slow pointer for write position, fast for scan
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — new array or hash set —
O(n)space extra. - Better — same two-pointer but confusing variable names.
- Optimal —
writeIndexstarts at 1; copy forward whennumbers[scan] != numbers[writeIndex-1]—O(n)time /O(1)extra space.
Optimal Solution
Go
package main
func removeDuplicates(numbers []int) int {
if len(numbers) == 0 {
return 0
}
writeIndex := 1
for scanIndex := 1; scanIndex < len(numbers); scanIndex++ {
if numbers[scanIndex] != numbers[writeIndex-1] {
numbers[writeIndex] = numbers[scanIndex]
writeIndex++
}
}
return writeIndex
}JavaScript
function removeDuplicates(numbers) {
if (numbers.length === 0) {
return 0;
}
let writeIndex = 1;
for (let scanIndex = 1; scanIndex < numbers.length; scanIndex++) {
if (numbers[scanIndex] !== numbers[writeIndex - 1]) {
numbers[writeIndex] = numbers[scanIndex];
writeIndex++;
}
}
return writeIndex;
}Walkthrough
Input: numbers = [0,0,1,1,1,2,2,3,3,4]
| scanIndex | writeIndex | compare with prev unique | action |
|---|---|---|---|
| 1 | 1 | 0 vs 0 | skip duplicate |
| 2 | 1 | 1 vs 0 | write 1 at 1, wi++ |
| 3 | 2 | 1 vs 1 | skip |
| 4 | 2 | 1 vs 1 | skip |
| 5 | 2 | 2 vs 1 | write 2, wi++ |
Final prefix [0,1,2,3,4,...] length 5.
Edge Cases
- Empty array → 0.
- All distinct → return
len(numbers). - Single element → 1.
Pitfalls
- Returning new slice instead of mutating in-place when required.
- Comparing with wrong prior element after compaction.
Similar Problems
- 027. Remove Element — same write-pointer pattern.
- 088. Merge Sorted Array — ordered merge discipline.
- 283. Move Zeroes — partition-style writes.
Variants
- Allow at most
kduplicates (LeetCode 80). - Linked list dedupe.
Mind-Map Tags
#two-pointers #sorted #dedupe #in-place
Last updated on
Spotted something unclear or wrong on this page?