The Remove Duplicates from Sorted Array II interview question is a variation of the classic deduplication problem. Given a sorted array, you must remove duplicates in-place such that each unique element appears at most twice. Elements beyond the cutoff do not matter. You must do this in O(1) extra space, returning the new length.
This problem is asked at Apple, Uber, Microsoft, Meta, Amazon, Google, and Bloomberg because it extends the basic two-pointer technique with a generalized condition. It tests whether candidates can adapt a known pattern to a new constraint rather than memorizing a single solution. The underlying concept — allowing at most k occurrences — is a template directly applicable to similar constraints.
The pattern is the generalized two-pointer technique. Maintain a write pointer k. For each element nums[i], compare it with nums[k-2] (the element two positions behind the write head). If they differ, it's safe to include nums[i] — write it at position k and advance k. If nums[i] == nums[k-2], it means we already have two copies and must skip. This generalizes to "at most k copies" by comparing with nums[write - k].
Array: [1, 1, 1, 2, 2, 3], at most 2 allowed.
[1,1,...].nums[2]=1 == nums[k-2]=nums[0]=1 → skip.nums[3]=2 ≠ nums[k-2]=nums[1]=1 → write 2 at k=2, k=3.nums[4]=2 ≠ nums[k-2]=nums[2-1]... wait → k=3 now, nums[k-2]=nums[1]=1 ≠ 2 → write 2, k=4.nums[5]=3 ≠ nums[k-2]=nums[2]=2 (now it's the 2 we wrote) → write 3, k=5.Result length: 5. Array: [1, 1, 2, 2, 3].
k to 2 to allow the first two elements through unconditionally.nums[write - k].For the Remove Duplicates from Sorted Array II coding problem, think of it as a template: the two-pointer array interview pattern with a configurable "allowed count." Interviewers at TikTok and Adobe often follow up with "what if at most 3 copies were allowed?" — show you can immediately adjust the index offset from 2 to 3. This demonstrates you understand the principle, not just the answer.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Next Permutation | Medium | Solve | |
| Number of Subarrays with Bounded Maximum | Medium | Solve | |
| Product of Two Run-Length Encoded Arrays | Medium | Solve | |
| Find Indices With Index and Value Difference II | Medium | Solve | |
| Maximum Product of First and Last Elements of a Subsequence | Medium | Solve |