Question
Design a data structure to implement the following set of operations
get(x)
set(x, …)
begin()
commit()
end()
Example,
begin()
set(x,2)
begin()
set(x,3)
get(x) -> needs to return 3
begin()
set(x,6)
commit()
get(x) -> needs to return 6 because of commit call will pass to the parent scope.
end()
get(x) -> needs to return 2, as end() will conclude the child scope.
end()
Thoughts,
I basically dabbled between a HashMap and then after writing some code. I quickly made it succinct to have it just be a Linkedlist datastructure and an inner class that maintains a HashMap of all the keys and its latest values. Example
class Solution {
LinkedList<Level> levels.
.....
class Level {
HashMap<String, Integer> levelKeys
}
}
The above LinkedList data structure. The tail will have the latest scope and its keys values. But, if you cannot find the key in the latest scope, then you traverse back towards head until you find one. Perhaps you can optimize it further by keeping a cache of latest values.
Was my approach wrong? They said I dabbled between data structures and couldnt complete the final method get. Why did i get digned on completeness if the approach was correct for the given timeframe.