← Bytedance Interview Insights
Use a two-pointer technique: one pointer to scan the array and another to track the position for writing the next valid element. Since the array is sorted, duplicates are adjacent, so you can allow at most two occurrences by comparing the current element with the element two positions before the write pointer.
Pro tip: Clarify that the solution runs in O(n) time and O(1) extra space, and mention that the same pattern generalizes to allowing at most k duplicates by comparing with the element k positions back.
Confirm that the array is sorted, modification is in-place, and the order of unique elements must be preserved. Discuss edge cases like empty array, length 1, or all elements identical.
Explain that you'll use a read pointer to iterate through the array and a write pointer to place the next valid element. This avoids extra space and maintains O(n) time.
For each element at the read pointer, write it to the write pointer only if the write pointer is less than 2 (first two elements) or the current element is greater than the element at write pointer - 2. This ensures at most two duplicates.
Iterate through the array, apply the condition, and increment the write pointer when a write occurs. Return the write pointer as the new length.
Walk through a few examples (e.g., [1,1,1,2,2,3] -> length 5) to verify correctness. State that time complexity is O(n) and space complexity is O(1).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.