Airbnb questions

Key Sum Store

AirbnbMedium

Build a small key-value store in which a key holds either a plain integer or a sum of other keys. Write the class KeySumStore with these methods.

  • set_value(key, value) makes key hold the integer value.
  • set_sum(key, refs) makes key the sum of the current values of the keys listed in refs. A key listed several times counts that many times: ["C", "C", "A"] means 2 * C + A.
  • get_value(key) returns the integer key holds right now. For a sum key, it is the sum of its inputs' current values, and an input may itself be a sum key.

A sum is live: changing the value or definition of a key changes every sum that depends on it, directly or through other sums, from that moment on. Calling set_value or set_sum on a key that already exists replaces whatever the key was before, whether it was a plain value or a sum. set_value and set_sum return nothing.

Part 1: Keys, sums and live reads

Implement the three methods. For example, after set_value("A", 5), set_value("B", 10), set_sum("C", ["A", "B"]) and set_sum("D", ["C", "C", "A"]), get_value("C") is 15 and get_value("D") is 35. After set_value("A", 100), get_value("C") is 110 and get_value("D") is 320.

  1. Example 1
    init
    []
    operations
    [["set_value",["A",5]],["set_value",["B",10]],["set_sum",["C",["A","B"]]],["set_sum",["D",["C","C","A"]]],["get_value",["C"]],["get_value",["D"]],["set_value",["A",100]],["get_value",["C"]],["get_value",["D"]]]
    Output
    [null,null,null,null,15,35,null,110,320]

    Why: C = A + B = 15 and D = C + C + A = 15 + 15 + 5 = 35. After A becomes 100, C = 110 and D = 110 + 110 + 100 = 320: the update reaches D through C and also directly.

Constraints

  • 1 <= len(key) <= 20
  • -10^9 <= value <= 10^9
  • 1 <= len(refs) <= 50
  • Every key in refs, and every key passed to get_value, was set by an earlier call.
  • No call makes a key depend on itself, directly or through other keys.
  • Every sum that is ever read fits in a signed 64-bit integer.
  • At most 10^5 calls in total.
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Key Sum Store: Airbnb interview question | LoopCoach