KatInterview

Check Loan Records for Proper Borrow-Return Order

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashinghash-setstate-trackingsimulation

Last updated

Scan a time-ordered list of library events and verify each item's history strictly alternates borrow, return, starting with a borrow, using per-item state tracking.

A library records every loan activity in a single list, already sorted from earliest to latest. Each record is a three-element list [time, item_id, is_borrow]:

  • time is the moment of the event. It is informational only.
  • item_id identifies the item involved (a string or an integer).
  • is_borrow is true when the item was borrowed and false when it was given back.

Write a function that decides whether the log is consistent.

Look at the events of any single item in the order they appear. That item's history is valid when:

  1. its first event is a borrow,
  2. borrows and returns then strictly alternate (borrow, return, borrow, return, ...), and
  3. no return occurs while the item is not currently borrowed.

Events of different items may be interleaved arbitrarily and do not affect each other. An item may still be borrowed when the log ends, which is perfectly fine.

Return True if the history of every item is valid, otherwise False. An empty log is valid.

Process the events in the given order; do not re-sort them.

Constraints

  • 0 <= len(logs) <= 10^5
  • Each record has exactly three entries: [time, item_id, is_borrow].
  • item_id values are hashable (strings or integers).
  • is_borrow is a boolean.
  • Records are already in chronological order.

Examples

Example 1

Input: check_loan_log([[1, 'a', True], [2, 'a', False], [3, 'a', True], [4, 'a', False]])

Output: True

Example 2

Input: check_loan_log([[1, 'a', False]])

Output: False

Example 3

Input: check_loan_log([[1, 'a', True], [2, 'a', True]])

Output: False

Hints

Hint 1

Consider the two states an item can be in: on the shelf or borrowed. Every item starts on the shelf.

Hint 2

Each event type is only legal from one state: a borrow needs the item on the shelf, a return needs it borrowed. Anything else makes the log invalid.

Hint 3

A set of currently borrowed item ids is enough. Check membership before adding or removing, and return False at the first violation.