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)makeskeyhold the integervalue.set_sum(key, refs)makeskeythe sum of the current values of the keys listed inrefs. A key listed several times counts that many times:["C", "C", "A"]means2 * C + A.get_value(key)returns the integerkeyholds 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.
- 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 = 15andD = C + C + A = 15 + 15 + 5 = 35. AfterAbecomes 100,C = 110andD = 110 + 110 + 100 = 320: the update reachesDthroughCand also directly.
Constraints
1 <= len(key) <= 20-10^9 <= value <= 10^91 <= len(refs) <= 50- Every key in
refs, and every key passed toget_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.