Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Riot Games

Compact a sorted array in place — Riot uses this for two-pointer fluency before state-replication delta questions.

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

Problem

Given a sorted array, remove duplicates in place such that each unique element appears once. Return the new length; the first k elements of the array must be the unique values.

Constraints

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

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 + copy back

Build a set, copy 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-pointer write index

Advance a write pointer only when nums[i] differs from nums[write-1].

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

Tradeoff:

Riot Games-specific tips

Riot graders favor the in-place compaction because matchmaking replication frames are dedup-compacted the same way before being broadcast on the server tick rate.

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

Practice these live with InterviewChamp.AI →