Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Spotify

Remove duplicates in place from a sorted array and return the new length.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a sorted integer array nums, remove duplicates in place such that each unique element appears only once. Return the count k of unique elements; the first k slots of nums must hold them in order.

Constraints

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

Examples

Example 1

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

Example 2

Input
nums=[0,0,1,1,1,2,2,3,3,4]
Output
5 with nums=[0,1,2,3,4,...]

Approaches

1. Brute force

Copy unique values to a Set then write back

Time
O(n)
Space
O(n)
const set = new Set(nums);
const arr = [...set];
for (let i=0;i<arr.length;i++) nums[i]=arr[i];
return arr.length;

Tradeoff:

2. Two pointers in place

Slow pointer marks next unique slot, fast pointer scans. O(1) extra space.

Time
O(n)
Space
O(1)
function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let slow = 0;
  for (let fast = 1; fast < nums.length; fast++) {
    if (nums[fast] !== nums[slow]) {
      slow++;
      nums[slow] = nums[fast];
    }
  }
  return slow + 1;
}

Tradeoff:

Spotify-specific tips

Spotify graders watch for in-place mutation discipline since track-history compaction and rolling listening logs use the exact same two-pointer rewrite pattern.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Remove Duplicates from Sorted Array and other Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →