Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Wise

Dedup a sorted array in place — Wise sometimes wraps this around deduping repeated FX quote ticks before they hit the matching engine.

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

Problem

Given a sorted array nums, remove duplicates in place such that each unique element appears once and return the new length. You must do it with O(1) extra space.

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. Set-based brute force

Push uniques into a Set then rewrite.

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

Tradeoff:

2. Two-pointer in place

Slow pointer marks next write slot; fast pointer scans.

Time
O(n)
Space
O(1)
function dedup(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:

Wise-specific tips

Wise asks about FX tick streams — point out that idempotent dedup is what keeps a noisy rate feed from inflating the order book.

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

Practice these live with InterviewChamp.AI →