ExamAdda Logo

Remove Duplicates from Sorted Array

Easy

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.

Return the number of unique elements in nums.

The first k elements of nums should contain the unique elements, where k is the returned value.

Example 1

Input

nums = [1,1,2]

Output

2
[1,2]

Explanation

The unique elements are [1,2].

The first 2 positions of nums should contain:

[1,2]

Example 2

Input

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

Output

5
[0,1,2,3,4]

Explanation

The unique elements are:

[0,1,2,3,4]

 

So k = 5.

Constraints

1 <= nums.length <= 3 * 10^4
-100 <= nums[i] <= 100
nums is sorted in non-decreasing order.

Hints:

Hint 1

Since the array is already sorted, equal elements will always be next to each other.

Hint 2

Use one pointer to scan the array and another pointer to place each new 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

Aug 19, 2026

Last updated

Aug 19, 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