PPractick

DSA interview question

Remove Duplicates from a Sorted Array

Easy · Algorithms · Topics: array, two pointer

The problem

A mailing service keeps subscriber IDs in a sorted array, and a bug in the import job left some IDs repeated. Memory on the device is tight, so the clean-up must happen in place: rearrange the array so each distinct ID appears once at the front, in order, and return how many distinct IDs there are. Whatever sits after that point doesn't matter. Because the array is sorted, duplicates are always next to each other, which makes a two-pointer pass possible: one pointer reads, the other writes.

Example: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] → returns 5, and the array starts with [0, 1, 2, 3, 4].

Function signature

int removeDuplicates(vector<int>& a);  // returns k; a[0..k-1] holds the distinct values in order

Test cases

Input aOutput kFirst k elementsExplanation
[1, 1, 2]2[1, 2]
[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]5[0, 1, 2, 3, 4]
[1, 2, 3]3[1, 2, 3]Already distinct: nothing changes
[2, 2, 2]1[2]All the same
[7]1[7]
[]0[]

(Confirm: the input is sorted in non-decreasing order; O(1) extra space; elements after position k can be anything.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the array sorted? (The two-pointer trick depends on it.)
  2. Must it be in place with O(1) extra space?
  3. Does anything after the first k positions matter?
  4. Can the array be empty?

Follow-ups to expect

  1. "Why does sortedness matter?"
  2. "What if each value may appear at most twice?"
  3. "Why not use a set?"
  4. "What about std::unique?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in