← Questions
Remove duplicates from a sorted array in place
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Apr 2026. It tests arrays and two pointers.
Given a sorted (non-decreasing) integer array, rearrange it in place so that each distinct value appears once at the front, in the original order, and return how many distinct values there are. What is left after that prefix doesn't matter. Use O(1) extra space.
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.
Example
nums = [1, 1, 2]
remove_duplicates(nums) -> 2 # nums[:2] == [1, 2]
nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
remove_duplicates(nums) -> 5 # nums[:5] == [0, 1, 2, 3, 4]
remove_duplicates([]) -> 0
Constraints
-
0 <= len(nums) <= 10^5; sorted in non-decreasing order. -
O(n)time andO(1)extra space.
Clarifying questions
- Is the array sorted? Ascending?
- Must the order of distinct values be kept?
- Does the tail after
kneed any particular content? - Can the array be empty?
What a strong answer covers
- A write pointer: scan with a read pointer and copy
nums[read]tonums[write]whenever it differs from the last written value. - Why comparing with the last written value (not the previous element) is the robust choice.
-
O(n)time,O(1)space, and why a set would break the space bound. - Tests: empty, one element, all equal, all distinct.
Follow-ups
- Allow each value at most
ktimes (compare withnums[write - k]). - The array is unsorted: what changes, and what does it cost?
- Remove all copies of a given value in place.
Where it's asked
- Meta · AI-enabled coding · Last asked Apr 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
arrays · two pointers
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
