Skip to main content
Back to problems
Leetcode
Medium
Arrays
Two Pointers
Remove Duplicates From Sorted Array

Remove duplicates from a sorted array in-place and return the count of unique elements.

Acceptance 76%
Problem Statement

Problem

You are given a non-decreasing sorted integer array nums. Remove the duplicates in-place so that each distinct value appears exactly once in the beginning of the array.

After the operation, the first part of nums should contain the unique values in the same relative order. The remaining portion of the array does not matter.

Return the number of unique elements.

Goal

Modify the array using only O(1)O(1) extra space and keep the operation efficient.

Example behavior

If nums = [1,1,2], after processing the array may become [1,2,_] and the function should return 2.

If nums = [0,0,1,1,1,2,2,3,3,4], after processing the array may become [0,1,2,3,4,_,_,_,_,_] and the function should return 5.

Input Format

  • A single integer array nums sorted in non-decreasing order.

Output Format

  • Return an integer k, the number of unique values.
  • The first k positions of nums should contain the unique values after in-place modification.

Constraints

  • nums is sorted in non-decreasing order.
  • You must modify the array in-place.
  • Use O(1)O(1) extra space.
  • The order of the unique elements must be preserved.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,1,2]

Output

2

Explanation

The unique values are [1,2]. After updating in place, the first two positions contain these values.

Example 2

Input

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

Output

5

Explanation

The unique values are [0,1,2,3,4]. The array is modified in place so those values occupy the first five positions.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.