← Bytedance Interview Insights
The two-pointer setup clicked pretty fast for me.
Use a two-pointer technique: one pointer (write) tracks the position where the next valid element should be placed, and the other (read) scans the array. Since each element can appear at most twice, compare the current element with the element at write-2; if different, copy it to write and increment write. Return write as the new length.
Pro tip: Clarify that the array is sorted and that 'in-place' means modifying the input array without using extra space. Mention that the solution generalizes to 'at most k duplicates' by comparing with write-k.
Restate the problem: remove duplicates in-place so each unique element appears at most twice, return the new length. Emphasize O(n) time and O(1) space.
Explain that since the array is sorted, duplicates are adjacent. Use a write pointer to overwrite invalid elements and a read pointer to scan.
For each element at read, check if write < 2 or if the element differs from the element at write-2. If so, copy it to write and increment write.
Trace the algorithm on a sample array like [1,1,1,2,2,3] to show how the write pointer advances and the array is modified.
State that time is O(n) because each element is read once, and space is O(1) since only two pointers are used. Discuss edge cases like empty array or array with length <=2.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.