← Questions
Remove duplicates in place from an unsorted array
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's coding round, last asked Feb 2026. It tests arrays, hashing and in-place.
Remove repeated values from an unsorted integer array in place. Keep the first occurrence of each value, in its original order, at the front of the array, and return how many values remain. What lies beyond that length does not matter.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
remove_duplicates(nums: list[int]) -> int— returnsk; afterwardsnums[:k]holds the distinct values in order of first appearance.
Example
nums = [4, 1, 4, 2, 1, 3, 2]
remove_duplicates(nums) -> 4 # nums[:4] == [4, 1, 2, 3]
nums = [7, 7, 7]
remove_duplicates(nums) -> 1 # nums[:1] == [7]
nums = []
remove_duplicates(nums) -> 0
Constraints
-
0 <= len(nums) <= 10^5; values fit in 32-bit integers. - In place: do not build a second output array.
Clarifying questions
- Must the original order of first occurrences be kept?
- Is extra memory such as a hash set allowed, or only O(1) extra space?
- Is the range of values small enough for a bitmap?
What a strong answer covers
- A write pointer plus a hash set of seen values: O(n) time, O(d) extra space for d distinct values.
- With O(1) extra space and order kept: compare each element with the kept prefix, O(n^2) time.
- With O(1) extra space and order not required: sort in place, then compact adjacent duplicates in O(n log n).
- A bitmap or counting array when the value range is small.
- The trade-off stated clearly for each variant, and tests for empty input, all equal, and no duplicates.
Follow-ups
- Allow each value to appear at most twice.
- The array is sorted: do it in O(n) time and O(1) space.
- Remove every value that appears more than once, keeping only the unique ones.
Where it's asked
- Microsoft · Coding · Last asked Feb 202660 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
