Key Sum Store

Asked at Airbnb

Reported by the problem's creator, not verified

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.

Examples

  1. Example 1

    Input: 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]

    Explanation: 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.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.