Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Ola

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

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

Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements; the order of the first k elements should match a deduplicated input.

Constraints

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

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. Brute force with set

Copy into a Set and write back.

Time
O(n)
Space
O(n)
const set = new Set(nums);
let i = 0;
for (const v of set) nums[i++] = v;
return set.size;

Tradeoff:

2. Two pointers

Slow pointer marks last unique; fast pointer scans; copy when new value found.

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:

Ola-specific tips

Ola interviewers like the two-pointer pattern because deduping sorted driver-pings is part of the real telemetry pipeline; show the in-place write.

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

Practice these live with InterviewChamp.AI →