Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Remove duplicates allowing at most two occurrences

Given a sorted array, remove duplicates in-place allowing each element to appear at most twice. Return the resulting prefix as a list.

Python practice32 minTwo Pointers & Sliding WindowAdvancedLast updated March 26, 2026

Problem statement

Given a sorted list nums, modify it in-place so that each unique element appears at most twice. After the modification, return the first part of the list that contains the allowed elements (i.e., the prefix up to the new length). For the purposes of automated testing, return that prefix as a new list. Aim for O(n) time and O(1) extra space (aside from the returned slice).

Task

Implement the two-pointer technique to compress a sorted array in-place so each value appears no more than twice; return the kept portion as a list for verification.

Examples

Example with more than two duplicates

Input

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

Output

[1, 1, 2, 2, 3]

Each number is allowed at most two times. The first three 1s become two 1s.

Input format

A sorted list of integers nums (may be empty).

Output format

A list representing the prefix of nums after removing extra duplicates (each value appears at most twice).

Constraints

Perform the operation in O(n) time and O(1) extra space (modifying nums in place). Return the kept prefix as a list for testing convenience.

Samples

Sample 1

Input

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

Output

[0, 0, 1, 1, 2, 3, 3]

Trim extra occurrences so each number appears at most twice.