Can someone tell me which data structure supports insert/delete/maximum operation in O(1)?
Can someone tell me which data structure supports insert/delete/maximum operation in O(1)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is a classical interview question, and is usually presented like this:
The answer is, you use two stacks: the main stack, and a min (or max) stack.
So for example, after pushing 1,2,3,4,5 onto the stack, your stacks would look like this:
However, if you were to push 5,4,3,2,1, the stacks would look like this:
For 5,2,4,3,1 you would have:
and so on.
You can also save some space by pushing to the min stack only when the minimum element changes, iff the items are known to be distinct.