62. Remove Duplicates from Sorted Array II
mediumAsked at RedditAllow at most two occurrences of each value in a sorted array, in-place. Reddit uses this to test slow/fast pointer with a count threshold — the same shape as rate-limiting to N per user in their abuse pipeline.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Reddit loops.
- Glassdoor (2026-Q1)— Reddit phone screen, two-pointer variant.
Problem
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Return k after placing the final result in the first k slots of nums.
Constraints
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^4nums is sorted in non-decreasing order.
Examples
Example 1
nums = [1,1,1,2,2,3]5Explanation: nums becomes [1,1,2,2,3,_].
Example 2
nums = [0,0,1,1,1,1,2,3,3]7Approaches
1. Track count per value
Iterate; count consecutive duplicates; copy only when count <= 2.
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
let k = 0, count = 0;
for (let i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] === nums[i - 1]) count++;
else count = 1;
if (count <= 2) nums[k++] = nums[i];
}
return k;
}Tradeoff: Clear and explicit. Works.
2. Compare against k - 2 (optimal)
Copy nums[i] to nums[k] only if k < 2 or nums[i] != nums[k - 2].
- Time
- O(n)
- Space
- O(1)
function removeDuplicates(nums) {
let k = 0;
for (const n of nums) {
if (k < 2 || n !== nums[k - 2]) nums[k++] = n;
}
return k;
}Tradeoff: Elegant — the k-2 lookback encodes the 'at most twice' rule directly.
Reddit-specific tips
Reddit interviewers love the k-2 lookback. Bonus signal: generalize to 'at most M occurrences' by comparing against nums[k - M]. Same shape as their per-user rate limit configurable at runtime.
Common mistakes
- Off-by-one on k - 2 (must check k < 2 first).
- Updating count before checking it.
- Not iterating over n directly (passing nums.length without const n).
Follow-up questions
An interviewer at Reddit may pivot to one of these next:
- Remove Duplicates from Sorted Array (LC 26).
- At most M duplicates — generalize.
- Remove duplicates from sorted list II (LC 82) — same on linked list.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why does k - 2 work?
If nums[i] equals nums[k - 2], then nums[k - 2] and nums[k - 1] are the same value already — adding a third would violate the rule.
Generalize to M?
Replace k < 2 with k < M and nums[k - 2] with nums[k - M].
Practice these live with InterviewChamp.AI
Drill Remove Duplicates from Sorted Array II and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →