I have a stack of elements from which a random element has to be removed (i.e. all the elements which are between the top and that particular element will be popped and pushed again). And every time an element is popped, we have to determine how many times it has been popped earlier for other elements.
I have been on this since a long while. (The stack is dynamic (i.e. elements are being added and removed from time to time)).
I would store the stack as a singly linked list, and keep an integer in each node to represent the number of times it’s been accessed. IE, a stack with 5 on top, 7 on the bottom and no accesses made would look like:
Then you could write your own pop (O(n)) which just iterates through the linked list adding 1 to access count for each node it visits (if you can assume that what you pop is always in the stack, then you only need to iterate through it once, if not you may need to iterate through twice) such that pop(3): // Returns 0
pop(7): // Returns 0
pop(2): // Returns 2
push(6):
pop(1): // Returns 1
pop(6): // Returns 1
pop(5): // Returns 4