Layered Settings
Medium · stack
A theme editor keeps named numeric settings in layers. There is always a base layer, and begin opens a new empty layer on top of the others. You are given a list of commands to run in order. Each command is one of:
"set name value": setnametovaluein the top layer. If the top layer already setsname, the old value in that layer is replaced. Values in lower layers are left alone, but are hidden while the top layer setsname."get name": read the current value ofname, which is the value in the topmost layer that sets it, or-1if no open layer sets it."begin": open a new empty layer on top."end": close the top layer and throw away everything set in it. Values it hid become visible again."end"is never used when only the base layer is open.
name is 1 to 8 lower-case letters and digits, and value is a whole number from 0 to 10^9. Return a list with the answer to every "get" command, in the order they appear.
Examples
Example 1
Input: commands = ["set a 5", "begin", "set a 7", "get a", "end", "get a", "get b"]
Output: [7, 5, -1]
Inside the new layer a is 7, hiding the 5. After end the 5 is visible again, and b was never set.
Example 2
Input: commands = ["begin", "set x 1", "begin", "get x", "set y 2", "end", "get y", "end", "get x"]
Output: [1, -1, -1]
x is visible through both layers. y disappears when its layer ends, and x disappears when the outer layer ends.
Example 3
Input: commands = ["set a 1", "set a 2", "get a"]
Output: [2]
Setting a name twice in the same layer replaces the earlier value.
Constraints
- 1 <= len(commands) <= 10^4
- Every command has one of the four forms above.
- name is 1 to 8 lower-case letters and digits; 0 <= value <= 10^9
- end is only used while at least one layer above the base layer is open.