DSA interview question
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].
int removeDuplicates(vector<int>& a); // returns k; a[0..k-1] holds the distinct values in order
Input a | Output k | First k elements | Explanation |
|---|---|---|---|
[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.)
set?"std::unique?"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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in