interview, stack, queue,

Cracking the coding interview - Stacks and Queues

Tony Tony Follow Aug 12, 2019 · 1 min read
Cracking the coding interview - Stacks and Queues
Share this

Introduction

Questions

  1. Three in One:Describe how you could use a single array to implement three stacks.
  2. Stack Min:How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
  3. Stack of Plates:Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() shold return the same values as it would if there were just a single stack).
    FOLLOW UP
    Implement a fucntion popAt(int index) whichperforms a pop operation on a specific sub-stack.
  4. Queue via Stacks:Implement a MyQueue class which implements a queue using two stacks.
  5. Sort Stack:Write a program to sort a stack such that the smallest items are on the top. you can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek and isEmpty.
  6. Animal Shelter:An animal shelter, which holds only dogs and cats, operates on a strictly “first in , first out” basis. People must adopt either the “oldest” (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat ( and will receive the oldest animal of that type). They cannot select which specifi canimal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in LinkedList data structure.

    Hints

    Solution

  7. Three in One:
  8. Stack Min:
  9. Stack of Plates:
  10. Queue via Stacks:
  11. Sort Stack:
  12. Animal Shelter:
Join Newsletter
Get the latest news right in your inbox. We never spam!
Tony
Written by Tony Follow
Hi, I am Tony, the author of Learning Journey blog. I hope you like what I sharing!