15% off all plans & roadmaps Use code
See plansRemove Duplicates from Sorted Array
- LeetCode 26
- Easy
- Two Pointers
- In-place Array Modification
Updated
TL;DR: Walk the sorted array with a read pointer and a write pointer, copying each value the first time it appears. The write pointer marks the next free slot, so one pass and O(1) extra space are enough.
Problem
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 stay the same. Return the number of unique elements, k, in nums.
The judge checks the result in a specific way. It reads the first k elements of nums and compares them with the expected unique values, in order. Values after index k - 1 are ignored, so you do not need to clear them. The starter code names the array parameter A, while the examples call it nums.
Example 1
Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: The function returns k = 2. The first two elements are 1 and 2. The underscore marks a slot whose value does not matter.
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] Explanation: The function returns k = 5. The first five elements are 0, 1, 2, 3, 4. Values after them do not matter.
Constraints
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100numsis sorted in non-decreasing order.
Constraints that matter
- n up to 3 * 10^4 rules out the shifting loop in the worst case. About n^2 / 2, roughly 4.5 * 10^8, element moves is too slow for a judge.
- The array is sorted in non-decreasing order, so duplicates form one block. You only need to compare each value with its neighbour or with the last value you kept.
- Values lie between -100 and 100. A counting table would work, but it depends on that range. Neighbour comparison works for any sorted values.
- The length is at least 1, so
A[0]always exists and is always kept. The loop can start at index 1 with no empty-array check.
Hints
Hint 1
The problem asks for in-place removal with O(1) extra space, and the input is sorted.
Hint 2
Scan from index 1 and compare each value with the one before it.
Solution
Intuition
The problem asks for in-place removal with O(1) extra space, and the input is sorted. Sorted input means equal values sit in one block. A value is new exactly when it differs from the last value you kept, so no hash set is needed.
Picture a sorted deck where copies sit together, and you deal only the first card of each rank onto a table pile. The pile is the prefix, its next empty spot is the write pointer, and the cards you never deal are the skipped duplicates.
The pattern is Two Pointers, in the in-place array modification subpattern. The signal is that you must change an array and keep only some of its elements. One pointer reads every element. The other marks where the next kept element goes.
The write pointer can overwrite safely because it never moves past the read pointer. Every slot it writes to has already been read, so no value you still need is lost. The result is a prefix of the same array.
The obvious first idea treats each duplicate as a deletion and closes the gap. That costs a full shift per duplicate. The two-pointer version never deletes anything. It only overwrites, and each kept value costs one assignment.
Worked example
Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] Output: 5, with the first five elements equal to [0, 1, 2, 3, 4] Explanation: The array has five distinct values, 0 through 4. Each value appears in one contiguous block, so the solution keeps the first element of each block. The function returns 5, and the slots after index 4 can hold anything.
Approach 1: Brute force with shifting
Scan from index 1 and compare each value with the one before it. When the two match, the value is a duplicate, so remove it by shifting every later element one slot to the left. The value that moves into index i has not been checked yet, so do not advance i after a shift.
This is the direct way to delete from an array, and a beginner writes it first because it matches the wording of the problem. It is correct, but every removal costs a full pass over the tail.
Steps
- Set
nto the array length. This is the logical length. - Set
ito 1. - While
i < n, compareA[i]withA[i - 1]. - If they are equal, shift
A[i + 1]throughA[n - 1]one slot left, then decreasenby 1. Do not changei. - If they differ, increase
iby 1. - Return
n.
Dry run
Run on [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]. Each line shows the array after one removal. Five removals happen, and 23 element moves happen in total.
- Removal 1 at i = 1: shift 8 elements. The array becomes
[0, 1, 1, 1, 2, 2, 3, 3, 4, 4], with n = 9. - Removal 2 at i = 2: shift 6 elements. The array becomes
[0, 1, 1, 2, 2, 3, 3, 4, 4, 4], with n = 8. - Removal 3 at i = 2: shift 5 elements. The array becomes
[0, 1, 2, 2, 3, 3, 4, 4, 4, 4], with n = 7. - Removal 4 at i = 3: shift 3 elements. The array becomes
[0, 1, 2, 3, 3, 4, 4, 4, 4, 4], with n = 6. - Removal 5 at i = 4: shift 1 element. The array becomes
[0, 1, 2, 3, 4, 4, 4, 4, 4, 4], with n = 5.
No equal neighbours remain, so the loop ends and returns 5.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the array length. A single removal shifts at most n - 1 elements, and there are at most n - 1 removals, so the total work is at most about n^2. An array of equal values reaches this bound, because removal t shifts roughly n - t elements and those counts sum to about n^2 / 2. The loop does constant work per index, and only i and n are extra variables, so the space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def removeDuplicates(self, A: List[int]) -> int:
n = len(A) # logical length, shrinks as duplicates are removed
i = 1
while i < n:
if A[i] == A[i - 1]:
# Shift everything after i one step left over the duplicate
for j in range(i, n - 1):
A[j] = A[j + 1]
n -= 1
else:
i += 1
return nJavaTested in our runner
class Solution {
public int removeDuplicates(int[] A) {
int n = A.length; // logical length, shrinks as duplicates are removed
int i = 1;
while (i < n) {
if (A[i] == A[i - 1]) {
// Shift everything after i one step left over the duplicate
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& A) {
int n = A.size(); // logical length, shrinks as duplicates are removed
int i = 1;
while (i < n) {
if (A[i] == A[i - 1]) {
// Shift everything after i one step left over the duplicate
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @return {number}
*/
var removeDuplicates = function(A) {
let n = A.length; // logical length, shrinks as duplicates are removed
let i = 1;
while (i < n) {
if (A[i] === A[i - 1]) {
// Shift everything after i one step left over the duplicate
for (let j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
};GoTested in our runner
func removeDuplicates(A []int) int {
n := len(A) // logical length, shrinks as duplicates are removed
i := 1
for i < n {
if A[i] == A[i-1] {
// Shift everything after i one step left over the duplicate
for j := i; j < n-1; j++ {
A[j] = A[j+1]
}
n--
} else {
i++
}
}
return n
}C#Tested in our runner
public class Solution {
public int removeDuplicates(int[] A) {
int n = A.Length; // logical length, shrinks as duplicates are removed
int i = 1;
while (i < n) {
if (A[i] == A[i - 1]) {
// Shift everything after i one step left over the duplicate
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
}The In-place Array Modification infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
In-place Array Modification
Part of Two Pointers
Approach 2: Two pointers with a write indexOptimalIn-place Array Modification
What's slow: the shifting approach pays for each duplicate by moving the whole tail again, so the same values are copied over and over. The insight that fixes it is that you never need to remove anything. Let the read index i scan the array once, and let the write index k mark the end of the unique prefix.
Copy A[i] to A[k] only when it differs from A[k - 1], the last value kept. Because k never passes i, every write lands on a slot that has already been read. The prefix A[0..k-1] always holds the unique values seen so far, in their original order.
Why it is correct. The prefix A[0..k-1] always holds the distinct values seen so far, in their original order. Because the input is sorted, equal values sit together, so a value differing from A[k-1] is one never kept before. Since k never passes i, each write only overwrites a slot that has already been read, so no needed value is lost.
Steps
- Set
kto 1.A[0]is always unique, so it stays where it is. - Loop
ifrom 1 ton - 1, reading each value once. - Compare
A[i]withA[k - 1], the last value kept. - If they differ, set
A[k] = A[i]and increasekby 1. - If they match, skip the value and move on.
- Return
k.
Dry run
Run on [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]. The table has one row per index i. The last column shows the kept prefix after that step.
| Step | i | A[i] | A[k - 1] | Action | k | Kept prefix A[0..k-1] |
|---|---|---|---|---|---|---|
| start | - | - | - | keep A[0] = 0 | 1 | [0] |
| 1 | 1 | 0 | 0 | equal, skip | 1 | [0] |
| 2 | 2 | 1 | 0 | differs, write A[1] = 1 | 2 | [0, 1] |
| 3 | 3 | 1 | 1 | equal, skip | 2 | [0, 1] |
| 4 | 4 | 1 | 1 | equal, skip | 2 | [0, 1] |
| 5 | 5 | 2 | 1 | differs, write A[2] = 2 | 3 | [0, 1, 2] |
| 6 | 6 | 2 | 2 | equal, skip | 3 | [0, 1, 2] |
| 7 | 7 | 3 | 2 | differs, write A[3] = 3 | 4 | [0, 1, 2, 3] |
| 8 | 8 | 3 | 3 | equal, skip | 4 | [0, 1, 2, 3] |
| 9 | 9 | 4 | 3 | differs, write A[4] = 4 | 5 | [0, 1, 2, 3, 4] |
The loop ends with k = 5, so the function returns 5. The slots after index 4 still hold old values, and the judge ignores them.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The loop runs n - 1 times, and each pass does a constant number of comparisons and at most one assignment, so the time is O(n). The method uses two integer indices, i and k, and writes into the input array, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def removeDuplicates(self, A: List[int]) -> int:
k = 1 # next write index; A[0] is always kept
for i in range(1, len(A)):
# Compare with the last kept value, not the previous read value
if A[i] != A[k - 1]:
A[k] = A[i]
k += 1
return kJavaTested in our runner
class Solution {
public int removeDuplicates(int[] A) {
int k = 1; // next write index; A[0] is always kept
for (int i = 1; i < A.length; i++) {
// Compare with the last kept value, not the previous read value
if (A[i] != A[k - 1]) {
A[k] = A[i];
k++;
}
}
return k;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& A) {
int n = A.size();
int k = 1; // next write index; A[0] is always kept
for (int i = 1; i < n; i++) {
// Compare with the last kept value, not the previous read value
if (A[i] != A[k - 1]) {
A[k] = A[i];
k++;
}
}
return k;
}
};JavaScriptTested in our runner
var removeDuplicates = function(A) {
let k = 1; // next write index; A[0] is always kept
for (let i = 1; i < A.length; i++) {
// Compare with the last kept value, not the previous read value
if (A[i] !== A[k - 1]) {
A[k] = A[i];
k++;
}
}
return k;
};GoTested in our runner
func removeDuplicates(A []int) int {
k := 1 // next write index; A[0] is always kept
for i := 1; i < len(A); i++ {
// Compare with the last kept value, not the previous read value
if A[i] != A[k-1] {
A[k] = A[i]
k++
}
}
return k
}C#Tested in our runner
public class Solution {
public int removeDuplicates(int[] A) {
int k = 1; // next write index; A[0] is always kept
for (int i = 1; i < A.Length; i++) {
// Compare with the last kept value, not the previous read value
if (A[i] != A[k - 1]) {
A[k] = A[i];
k++;
}
}
return k;
}
}Common mistakes
- Starting
kat 0 and then readingA[k - 1]. The index becomes -1. Python silently reads the last element, and C++ and Go read out of bounds. Startkat 1, becauseA[0]is always kept. - Forgetting
k++after the writeA[k] = A[i]. Every unique value then overwrites slot 1, and the example returns 1 withA[1]holding 4. Increasekin the same branch as the write. - Advancing
iafter a shift in the brute force, so the value that moved into positioniis never checked. On[1, 1, 1]this returns 2 instead of 1. Only advanceiwhen the two values differ. - Returning the original length after the brute-force shifts. The judge reads the returned value as the count, so return the logical length
nthat shrinks with each removal. - Reading
A[i + 1]in a loop that runs ton - 1, which goes out of range on the last index. The write-index method needs no lookahead, so compareA[i]withA[k - 1]and skip the bound check entirely. - Using a hash set or a second list to record seen values. That breaks the O(1) extra space requirement and adds nothing, because sorted input already tells you which value is new.
Edge cases
- A single element such as
[5]. The answer is 1 and the array is unchanged. - All values equal, such as
[7, 7, 7, 7]. The answer is 1, andA[0]stays 7. - No duplicates, such as
[-3, -1, 0, 2]. The answer is 4, and the array is unchanged. - Two equal values, such as
[1, 1]. The answer is 1. This is the smallest case where the loop does a comparison that matches. - Negatives and zero crossing, such as
[-100, -100, 0, 0, 100, 100]. The answer is 3, and the prefix is[-100, 0, 100]. - The maximum size of 3 * 10^4 with mostly equal values. The write-index method stays linear, while the shifting method does the most work here.
Follow-ups interviewers ask
- What if each value may appear at most twice?
- This is the LeetCode 80 variant. Return
ndirectly whennis 1 or 2. Otherwise startkat 2, and for eachifrom 2 keepA[i]when it differs fromA[k - 2]. In a sorted array, that check allows at most two copies of any value. - What if the array is not sorted?
- The neighbour check breaks, because equal values can sit far apart. Sorting first fixes that in O(n log n), but it changes the order, and the problem requires the original order. A hash set keeps the order and runs in O(n) time, but it uses O(n) extra space. Checking each element against the kept prefix keeps the order with O(1) extra space, but it takes O(n^2) time.
- What if the array does not fit in memory?
- Stream the values from disk in order, because sorted input keeps duplicates adjacent. Keep only the last value written, and write each new value to an output stream as you read it. Memory use stays constant. An in-place rewrite of a file is awkward, so the output goes to a second file.
Remove Duplicates from Sorted Array FAQ
What is the time complexity of Remove Duplicates from Sorted Array?
The two-pointer solution runs in O(n) time, because the read index visits each element once and does constant work per step. The shifting brute force runs in O(n^2) time in the worst case. Both use O(1) extra space.
Why use two pointers for Remove Duplicates from Sorted Array?
The array is sorted, so duplicates sit next to each other. You only compare each value with the last kept value. One pointer reads, one pointer writes, and the result builds at the front without a second array.
Can Remove Duplicates from Sorted Array be solved in O(1) extra space?
Yes. The two-pointer method stores only two integer indices and writes into the input array. It depends on the input being sorted, because only then do equal values sit together.
Do I need to clear the elements after index k?
No. The judge reads only the first k elements and the returned value. Leftover values after index k can stay as they are.
Why does the sorted order matter here?
Equal values must be adjacent for the neighbour check to find every duplicate. On an unsorted array, a value can repeat far from its first copy, so the check would keep it. You would need a hash set or a sort first.
Asked at
See which companies ask this — Pro
Related problems
- Remove Element · same technique: In-place Array Modification
- Merge Strings Alternately · same technique: In-place Array Modification
- Move Zeroes · same technique: In-place Array Modification
- Intersection of Two Arrays · same technique: In-place Array Modification
- Sort Array By Parity · same technique: In-place Array Modification
- Sort Colors · next harder, same pattern
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Reverse String · same pattern: Two Pointers
- Squares of a Sorted Array · same pattern: Two Pointers