ExamAdda Logo

Remove Duplicates from Sorted Array II

Easy

Given a sorted integer array nums, remove some duplicates in-place such that each unique element appears at most twice.

The relative order of the elements should be preserved.

Return the number of elements remaining after the removal.

The first k elements of nums should contain the final result.

Example 1

Input

6
1 1 1 2 2 3

Output

5
1 1 2 2 3

Explanation

The value 1 appears three times. Since each element can appear at most twice, one occurrence is removed.

The first five elements become 1 1 2 2 3.

Example 2

Input

9
0 0 1 1 1 1 2 3 3

Output

7
0 0 1 1 2 3 3

Explanation

Every unique element appears at most twice after removing the extra duplicates.

Constraints

1 ≤ n ≤ 3 × 10⁴
-10⁴ ≤ nums[i] ≤ 10⁴
nums is sorted in non-decreasing order.

Hints:

Hint 1

Since the array is sorted, duplicate values are adjacent.

Hint 2

Maintain a write pointer. Allow writing the current element only if it does not create more than two occurrences of the same value.

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 1, 2026

Last updated

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