Validate alternating checkout/return logs
Company: Meta
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to process sequential event logs, maintain per-entity state invariants (checkout vs return), and reason about algorithmic time and space complexity within a validation task.
Constraints
- 0 <= number of logs <= 10^5
- Each log is a tuple (timestamp, book_id, is_checkout).
- timestamps are unique integers; logs may be given in any order.
- book_id is a string; is_checkout is a boolean.
- An empty log list is valid (returns True).
Examples
Input: ([(1, 'b1', True), (2, 'b1', False), (3, 'b1', True), (4, 'b1', False)],)
Expected Output: True
Explanation: Single book b1: checkout, return, checkout, return — a clean alternation starting with a checkout.
Input: ([(1, 'b1', False)],)
Expected Output: False
Explanation: The only event for b1 is a return with no preceding checkout, so the sequence does not start with a checkout.
Input: ([(1, 'b1', True), (2, 'b1', True)],)
Expected Output: False
Explanation: Two checkouts in a row for b1 break strict alternation.
Input: ([(4, 'b1', False), (2, 'b1', True), (10, 'b1', True), (1, 'b1', False)],)
Expected Output: False
Explanation: After sorting by timestamp the order is (1,return),(2,checkout),(4,return),(10,checkout) — it starts with a return, which is invalid.
Input: ([(1, 'a', True), (2, 'b', True), (3, 'a', False), (4, 'b', False), (5, 'a', True)],)
Expected Output: True
Explanation: Two interleaved books: a = checkout,return,checkout and b = checkout,return; each book's own sequence is independently valid.
Input: ([(1, 'a', True), (2, 'b', False)],)
Expected Output: False
Explanation: Book b's first event is a return, so even though book a is fine, the overall result is False.
Input: ([],)
Expected Output: True
Explanation: Empty log list has no invalid sequences, so it is considered valid.
Input: ([(5, 'x', True), (1, 'x', True)],)
Expected Output: False
Explanation: After sorting, x has checkout at t=1 then checkout at t=5 — two consecutive checkouts, which breaks alternation.
Hints
- Sort the logs by timestamp first, since they can arrive out of order.
- Track, per book_id, whether the next expected event is a checkout or a return. The first expected event for any book is a checkout.
- If any event does not match the expected type for its book, the whole input is invalid. A return before any checkout is just the special case where the very first expected event (checkout) is violated.