Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Unity

Remove duplicates from a sorted array in place. Unity uses this to probe in-place mutation needed for asset-pipeline buffers.

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

Problem

Given a sorted array nums, remove duplicates in-place so each element appears once and return the new length. Modify the input array; extra space allocation is not allowed.

Constraints

  • 1 <= nums.length <= 3*10^4
  • nums 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. Filter into new array

Build a fresh array of unique values, then copy 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 in place

Write pointer copies forward when current differs from previous unique value.

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

Tradeoff:

Unity-specific tips

Unity grades for zero-allocation passes since asset-pipeline buffers must mutate in place to stay inside the frame budget.

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

Practice these live with InterviewChamp.AI →