Implement in-place duplicate removal
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in in-place array manipulation, handling duplicates in sorted sequences, and formal reasoning about space and time complexity.
Remove Duplicates from Sorted Array (In-Place)
Constraints
- 0 <= len(nums) <= 3 * 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in non-decreasing order
- Must modify nums in place with O(1) extra memory
Examples
Input: ([1, 1, 2],)
Expected Output: 2
Explanation: Unique prefix becomes [1, 2]; new length is 2.
Input: ([0, 0, 1, 1, 1, 2, 2, 3, 3, 4],)
Expected Output: 5
Explanation: Distinct values [0,1,2,3,4]; new length is 5.
Hints
- Keep one pointer for the position of the last unique value already written, and a second pointer that scans forward.
- Because the array is sorted, all copies of a value are contiguous — you only need to compare each element with the most recently written one.
- When nums[read] differs from nums[write - 1], write it at index `write` and increment `write`.
Remove Duplicates from Sorted Array II — At Most Twice (In-Place)
Constraints
- 0 <= len(nums) <= 3 * 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in non-decreasing order
- Each distinct value may appear at most twice in the result
- Must modify nums in place with O(1) extra memory
Examples
Input: ([1, 1, 1, 2, 2, 3],)
Expected Output: 5
Explanation: Third 1 is dropped; result prefix [1,1,2,2,3]; length 5.
Input: ([0, 0, 1, 1, 1, 1, 2, 3, 3],)
Expected Output: 7
Explanation: 1 appears 4 times -> kept twice; result [0,0,1,1,2,3,3]; length 7.
Hints
- Always keep the first two elements of any equal-value block, then drop the rest.
- Compare the current candidate against the element two slots before the write pointer (nums[write - 2]) instead of one slot back.
- Guard with `write < 2` so the first two writes are unconditional; this pattern generalizes to 'at most k copies' by comparing with nums[write - k].