bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 232. Implement Queue using Stacks

232. Implement Queue using Stacks

Leetcode Solutions

Approach # (Two Stacks) Push - O() per operation, Pop - Amortized O() per operation

  1. Initialize two stacks, s1 and s2.
  2. For push operation, push the element onto s1.
  3. For pop operation, if s2 is empty, transfer all elements from s1 to s2 by popping from s1 and pushing onto s2. Then pop the top of s2.
  4. If s2 is not empty, pop the top of s2 directly.
  5. For peek operation, if s2 is empty, transfer all elements from s1 to s2 and return the top of s2. If s2 is not empty, return the top of s2.
  6. For empty operation, check if both s1 and s2 are empty. If both are empty, the queue is empty.
UML Thumbnail

Approach # (Two Stacks) Push - O(n) per operation, Pop - O() per operation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...