Remove Duplicates from Sorted Array
Squeeze a sorted array so each value appears once, reusing the same array rather than building a new one.
Problem
Given an array sorted from smallest to largest, remove the repeats without making a new array, so each value appears only once. Return k, the count of different values. The first k slots must hold those values in their original order.
- Do not create a new array.
- Use O(1) extra space.
- Keep the original order.
Examples
Approach
- The first element is always unique, so start with k = 1.
- Walk a reading position from index 1 to the end.
- If nums[read] differs from the last kept value nums[k - 1], copy it to nums[k] and increment k.
- Because the array is sorted, duplicates sit next to each other, so comparing with the last kept value is enough.
Common mistakes
- Forgetting the empty array: return 0 before starting at k = 1.
- The values after index k are left as they were, not removed - callers must read only the first k.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned