Google questions

Locker Bank

GooglePhone screenMedium

A locker room has lockers numbered 1 to n. LockerBank(n) starts with every locker free. A customer is a string and holds at most one locker at a time. A freed locker can be handed out again immediately.

Each test drives one instance: init holds the constructor arguments and operations is a list of [method, [args]] calls; the output lists every call's return value.

Part 1: Store and pick up

Implement a class LockerBank with:

  • store(customer) gives the customer the smallest free locker and returns its number. It returns -1 and changes nothing if the customer already holds a locker or no locker is free.
  • pickup(customer) frees the customer's locker and returns its number, or returns -1 if the customer holds none.
  • last() returns the locker number from the most recent successful store, or -1 if there has been none. Failed calls and pickups do not change it.
  1. Example 1
    init
    [3]
    operations
    [["last",[]],["store",["ann"]],["store",["bo"]],["store",["ann"]],["store",["cy"]],["store",["dee"]],["last",[]],["pickup",["bo"]],["store",["dee"]],["last",[]],["pickup",["zed"]],["last",[]],["pickup",["ann"]],["pickup",["ann"]],["store",["ann"]],["last",[]]]
    Output
    [-1,1,2,-1,3,-1,3,2,2,2,-1,2,1,-1,1,1]

    Why: ann gets locker 1, bo gets 2, a second store for ann fails with -1, cy gets 3 and dee finds the bank full. After bo leaves locker 2, dee gets 2. Failed calls never change last(), which stays at the locker from the latest successful store.

Constraints

  • 1 <= n <= 2 * 10^5
  • 1 <= len(operations) <= 2 * 10^5
  • 1 <= len(customer) <= 10
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Locker Bank: Google interview question | LoopCoach