Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Yelp

Compact a sorted array in-place — Yelp's stand-in for collapsing duplicate review entries from the same user before downstream ranking.

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

Problem

Given a sorted integer array nums, remove duplicates in-place so that each unique element appears once. Return the count of unique elements. Order of remaining elements must be preserved.

Constraints

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

Examples

Example 1

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

Example 2

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

Approaches

1. Set + rewrite

Drop into a Set, write unique values back.

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

Tradeoff:

2. Two pointers

Track write index; advance only when value changes.

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

Tradeoff:

Yelp-specific tips

Yelp interviewers want the in-place two-pointer solution and will ask how the same pattern dedupes near-identical photo uploads on the same business listing.

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 Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →