Keep at Most Two Copies of Each Timestamp in a Sorted Log
Last updated: November 29, 2026
Quick Overview
A sorted array of event timestamps contains many repeats. Modify it in place so each timestamp appears at most twice, and return the new length.
0
0
0 solved
A sorted array of event timestamps contains many repeats. Modify it in place so each timestamp appears at most twice, and return the new length.
A Google online-assessment style in-place array question, framed around trimming duplicate retries in a sorted event log before shipping it to storage. The interviewer checks the read/write pointer invariant and whether the candidate generalizes it to at most k copies.
What the Interviewer Expects
- Uses a write pointer that compares with the element two slots back
- Explains why comparing with `nums[write - 2]` is enough
- Keeps the array in place with O(1) extra space
- Generalizes to at most k copies
- Returns the correct length
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Generalize to keep at most k copies.
- What if the log is not sorted?
- How would you do this for a log split across many files that are each sorted?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
ts, a list sorted ascending. - Rearrange in place so the first
Lentries hold the result, each value at most twice, in sorted order. - Return
L. Entries afterLdo not matter. - O(n) ...
High-Level Design
Let write be the length of the kept prefix. For each value v in order, keep it if write < 2 or v != ts[write - 2]. Since the prefix is sorted, if v equals the element two positions back, the...