Skip to main content

4. Remove Duplicates from Sorted Array

easyAsked at Coursera

In-place dedupe of a sorted array — Coursera tests two-pointer fluency in a learner-history dedupe scenario.

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. Order must be kept; extra memory not allowed.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • 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 + rebuild

Dump into a Set, write back.

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. Slow/fast pointers

Slow tracks next write slot; fast scans; write when fast value differs.

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

Tradeoff:

Coursera-specific tips

Coursera reviewers often ask you to extend this to deduping a sorted log of learner-progress events while preserving the most-recent state — show you can extend the pattern.

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

Practice these live with InterviewChamp.AI →