But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.
You're in!
You want to be able to access the largest element in a stack.
Use the built-in Stack class to implement a new class MaxStack with a method GetMax that returns the largest element in the stack. GetMax should not remove the item.
Your stacks will contain only integers.
What if we push several items in increasing numeric order (like 1, 2, 3, 4...), so that there is a new max after each Push? What if we then Pop each of these items off, so that there is a new max after each Pop? Your algorithm shouldn't pay a steep cost in these edge cases.
You should be able to get a runtime of for Push, Pop, and GetMax.
A just-in-time approach is to have GetMax simply walk through the stack (popping all the elements off and then pushing them back on) to find the max element. This takes time for each call to GetMax. But we can do better.
To get time for GetMax, we could store the max integer as a member variable (call it max). But how would we keep it up to date?
For every Push, we can check to see if the item being pushed is larger than the current max, assigning it as our new max if so. But what happens when we Pop the current max? We could re-compute the current max by walking through our stack in time. So our worst-case runtime for Pop would be . We can do better.
What if when we find a new current max (newMax), instead of overwriting the old one (oldMax) we held onto it, so that once newMax was popped off our stack we would know that our max was back to oldMax?
What data structure should we store our set of maxes in? We want something where the last item we put in is the first item we get out ("last in, first out").
We can store our maxes in another stack!
We define two new stacks within our MaxStack class—_stack holds all of our integers, and _maxesStack holds our "maxima." We use _maxesStack to keep our max up to date in constant time as we Push and Pop:
time for Push, Pop, and GetMax. additional space, where m is the number of operations performed on the stack.
Our solution requires additional space for the second stack. But do we really need it?
Can you come up with a solution that requires additional space? (It's tricky!)
Notice how in the solution we're spending time on Push and Pop so we can save time on GetMax. That's because we chose to optimize for the time cost of calls to GetMax.
But we could've chosen to optimize for something else. For example, if we expected we'd be running Push and Pop frequently and running GetMax rarely, we could have optimized for faster Push and Pop methods.
Sometimes the first step in algorithm design is deciding what we're optimizing for. Start by considering the expected characteristics of the input.
Reset editor
Powered by qualified.io