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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Easy

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
Two Pointers
In-Place Arrays
Deduplication
Sorted Arrays
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: ts, a list sorted ascending.
  • Rearrange in place so the first L entries hold the result, each value at most twice, in sorted order.
  • Return L. Entries after L do 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...


Submit Your Answer
Markdown supported