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)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.
Examples
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 = 15andD = C + C + A = 15 + 15 + 5 = 35. AfterAbecomes 100,C = 110andD = 110 + 110 + 100 = 320: the update reachesDthroughCand also directly.