#26EasyTwo Pointers

Remove Duplicates from Sorted Array

In-place deduplication of a sorted array using two pointers.

MicrosoftGoogleAmazonAdobe

Problem Statement

Given a sorted integer array nums, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements k. The first k elements of nums must contain the unique elements in order.

Examples

Example 1

Input:nums = [1,1,2]
Output:2, nums = [1,2,_]

Explanation: Two unique elements. First 2 positions hold [1,2].

Example 2

Input:nums = [0,0,1,1,1,2,2,3,3,4]
Output:5, nums = [0,1,2,3,4,_,_,_,_,_]

Constraints

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

Solutions

1
Extra Array
TimeO(n)SpaceO(n)

Build a new array with only unique elements and copy back. Doesn't satisfy the in-place constraint.

Visual Animation
def removeDuplicates(nums: list[int]) -> int:
    unique = list(dict.fromkeys(nums))
    for i, v in enumerate(unique):
        nums[i] = v
    return len(unique)

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems