Magicsheet logo

Remove Duplicates from Sorted Array

Easy
60.7%
Updated 6/1/2025

Remove Duplicates from Sorted Array

What is this problem about?

The Remove Duplicates from Sorted Array interview question is a foundational in-place array manipulation problem. Given a sorted array of integers, you must remove all duplicate values so that each element appears only once, modifying the array in-place and returning the new length. The elements beyond the new length do not matter. No extra array space is allowed.

Why is this asked in interviews?

This is one of the most frequently asked warm-up problems at companies like Apple, Uber, Microsoft, Meta, Amazon, and Google because it directly tests the two-pointer technique — one of the most versatile tools in array manipulation. It also evaluates whether candidates can think in terms of in-place modification, a concept relevant to memory-constrained systems and embedded software.

Algorithmic pattern used

The pattern is the two-pointer technique. Use a slow pointer k to track the position of the last unique element written, and a fast pointer i to scan through the array. Whenever nums[i] differs from nums[k], increment k and copy nums[i] to nums[k]. After the scan, k + 1 is the new length.

Example explanation

Array: [1, 1, 2, 3, 3, 4]

  • k=0 (value=1), i=1: nums[1]==nums[0] → skip.
  • i=2: nums[2]=2 ≠ nums[0]=1 → k=1, nums[1]=2. Array: [1,2,2,3,3,4].
  • i=3: nums[3]=3 ≠ nums[1]=2 → k=2, nums[2]=3.
  • i=4: nums[4]=3 == nums[2]=3 → skip.
  • i=5: nums[5]=4 ≠ nums[2]=3 → k=3, nums[3]=4.

New length: 4. First 4 elements: [1, 2, 3, 4].

Common mistakes candidates make

  • Using extra space (a separate array or set) instead of modifying in-place.
  • Off-by-one errors in the return value — returning k instead of k+1.
  • Not handling the edge case of an empty array (return 0 immediately).
  • Assuming the array is unsorted and trying to use a hash set unnecessarily.

Interview preparation tip

For the Remove Duplicates from Sorted Array coding problem, the two-pointer array interview pattern is essential to master. Practice explaining the role of each pointer before coding — fast pointer for reading, slow pointer for writing. This exact pattern extends to Remove Duplicates from Sorted Array II and Remove Element, so mastering it here builds a reusable mental model. Interviewers at Infosys and Wipro often use this as an entry-level screen, so practice explaining it in simple terms.

Similar Questions