Algorithms and Data Structures · Middle · Question 22 of 75

How do you implement a queue with two stacks so that each operation is amortized O(1)?

Explanation

Moving elements reverses their order, so the oldest ends up on top of "out". Each element is moved at most once, so n operations cost O(n) in total.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 22

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz