Meta questions

Library Checkout Log

MetaPhone screenMedium

A library records what happens to its books as a list of events. Each event is [timestamp, book_id, member_id, action], where timestamp is a decimal string of an integer and action is one of "checkout", "return" or "renew".

Part 1: Validate the log

You are given a checkout log events, where each event is [timestamp, book_id, member_id, action]. Return [True, -1] if the log is valid, or [False, i] where i is the index of the first event that breaks a rule.

The log is valid when all of the following hold:

  • A checkout is allowed only for a book no one currently holds; afterwards member_id holds the book.
  • A return or a renewal is allowed only for the member who currently holds the book. A return frees the book; a renewal keeps the holder unchanged. A return or renewal of a book no one holds is a violation.
  • For each book separately, its timestamps never decrease from one of its events to the next in the log. Equal timestamps are allowed, and events of different books may appear in any time order.

An empty log is valid.

  1. Example 1
    events
    [["1","b1","m1","checkout"],["2","b1","m1","renew"],["3","b1","m1","return"],["4","b1","m2","checkout"]]
    Output
    [true,-1]

    Why: m1 checks b1 out, renews it and returns it. After the return the book is free, so m2 may check it out at time 4. Every event is allowed, so the answer is [True, -1].

Constraints

  • 0 <= len(events) <= 10^5
  • Each timestamp is a decimal string of an integer with 0 <= int(timestamp) <= 10^12
  • action is "checkout", "return" or "renew"
  • No checkout event has the same member_id and book_id as an earlier checkout of that book that has not been followed by a return
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Library Checkout Log: Meta interview question | LoopCoach