ExamAdda Logo

Remove Elements from Sorted Array

Easy

Given a sorted integer array nums, remove all duplicate elements in-place such that each unique element appears only once.

The relative order of the elements should be maintained.

Return the number of unique elements.

The first k elements of the array should contain the unique elements after removing duplicates.

Example 1

Input

5
1 1 2 2 3

Output

3
1 2 3

Explanation

After removing duplicates, the unique elements are 1, 2, and 3.

The function returns 3 because there are three unique elements.

Example 2

Input

10
0 0 1 1 1 2 2 3 3 4

Output

5
0 1 2 3 4

Explanation

Each unique element appears only once in the first five positions of the array.

Constraints

1 ≤ n ≤ 10⁵
-10⁹ ≤ nums[i] ≤ 10⁹
nums is sorted in non-decreasing order.

Hints:

Hint 1

Since the array is already sorted, duplicate elements always appear next to each other.

Hint 2

Use two pointers. One pointer scans the array while the other keeps track of the position to place the next unique element.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Jul 29, 2026

Last updated

Aug 6, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output