Skip to content

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k. To get accepted, you need to do the following things:

  1. Change the array nums such that the first k elements of nums contain the unique elements in the order they were present initially.
  2. The remaining elements of nums are not important as well as the size of nums.
  3. Return k.
InputOutputExplanation
[1, 1, 2]2Array becomes [1, 2, _]. The first 2 elements are unique.
[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]5Array becomes [0, 1, 2, 3, 4, _, _, _, _, _]. The first 5 elements are unique.
  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.
ApproachTimeSpaceModifies ArrayBest When
Two Pointers In-PlaceO(n)O(1)YesGeneral case — single pass, no extra memory
Simple PassO(n)O(1)YesClarity over performance — easier to understand
  • Pick Two Pointers if you want the optimal, interview-ready solution.
  • Pick Simple Pass if you prefer clearer variable naming and explicit logic flow.
Best For Speed
Two Pointers In-Place
O(n) time · O(1) space
Clarity
Simple Pass
O(n) time · O(1) space
★ Recommended

Use two pointers: one to read unique elements and one to write them back. Since the array is sorted, duplicates are always consecutive. When we encounter a new unique element, write it to the write pointer and advance it.

The key insight is that we only need to check nums[i] != nums[i - 1]. If true, we found a new unique element and should write it to the position k.

⏱ Time O(n) Single pass 💾 Space O(1) No extra space

Input: nums = [1, 1, 2]

Stepinums[i]nums[i-1]Same?ActionkArray State
Start----Initialize1[1, 1, 2]
1111Skip, duplicate1[1, 1, 2]
2221Write nums[2] to nums[k=1], k++2[1, 2, 2]

Return k = 2, array first 2 elements: [1, 2]

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

Stepinums[i]Unique?ActionkProgress
Start---Initialize10 at k=0 is unique
110NoSkip1No change
221YesWrite to k=1, k++2[0, 1, ...]
331NoSkip2No change
441NoSkip2No change
552YesWrite to k=2, k++3[0, 1, 2, ...]
662NoSkip3No change
773YesWrite to k=3, k++4[0, 1, 2, 3, ...]
883NoSkip4No change
994YesWrite to k=4, k++5[0, 1, 2, 3, 4, ...]

Return k = 5

Animated walkthrough

How the two-pointer approach removes duplicates

Watch the write pointer (k) move forward only when a unique element is found. The read pointer (i) scans through the entire array.

Step 1 of 3
Waiting to begin...
Array state
Memory / lookup state

function removeDuplicates(nums):
if nums is empty:
return 0
k = 1 // First element is always unique
for i from 1 to len(nums) - 1:
if nums[i] != nums[i - 1]:
nums[k] = nums[i]
k = k + 1
return k
remove_duplicates_from_sorted_array_two_pointer.py
from typing import List
def removeDuplicates(nums: List[int]) -> int:
"""
Two-Pointer In-Place Approach
Remove duplicates from sorted array in-place and return the length of the new array.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums:
return 0
k = 1 # First element is always unique
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
nums[k] = nums[i]
k += 1
return k
# Test cases
print(removeDuplicates([1, 1, 2])) # 2, nums = [1, 2, _]
print(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])) # 5, nums = [0, 1, 2, 3, 4, _, _, _, _, _]
✓ Simple

Instead of tracking indices i and k, use explicit readIdx and writeIdx pointers with clearer semantics. This approach is functionally identical to the first but with more descriptive variable names.

⏱ Time O(n) Single pass 💾 Space O(1) No extra space

Input: nums = [1, 1, 2]

readIdxwriteIdxnums[readIdx]nums[writeIdx]ActionResult
Start0-1Initialize pointers-
1011Equal, skipNo change
2021Different, write nums[2] to nums[1], writeIdx++[1, 2, _]

Return writeIdx + 1 = 2

function removeDuplicates(nums):
if nums is empty:
return 0
writeIdx = 0
for readIdx from 1 to len(nums) - 1:
if nums[readIdx] != nums[writeIdx]:
writeIdx = writeIdx + 1
nums[writeIdx] = nums[readIdx]
return writeIdx + 1
remove_duplicates_from_sorted_array_simple.py
from typing import List
def removeDuplicates(nums: List[int]) -> int:
"""
Simple Pass Approach
Remove duplicates by iterating and comparing consecutive elements.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if not nums:
return 0
write_idx = 0
for read_idx in range(1, len(nums)):
if nums[read_idx] != nums[write_idx]:
write_idx += 1
nums[write_idx] = nums[read_idx]
return write_idx + 1
# Test cases
print(removeDuplicates([1, 1, 2])) # 2, nums = [1, 2, _]
print(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])) # 5, nums = [0, 1, 2, 3, 4, _, _, _, _, _]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
remove_duplicates_from_sorted_array_optimized.py
"""
Solution for Remove Duplicates from Sorted Array
"""
def solve():
"""Implementation for approach 3 of Remove Duplicates from Sorted Array"""
pass
if __name__ == "__main__":
print("Solution ready")