63 / 75
Use two stacks: push to stack1, pop/peek from stack2 (transfer when stack2 empty).
Example:
Input:
push(1), push(2), peek(), pop(), empty()Output:
[null, null, 1, 1, false]Common Mistakes:
- Transferring on every operation (amortized O(1) lost)
- Not checking if output stack is empty before transferring
- Duplicating transfer logic in pop and peek
- Wrong empty condition (must check both stacks)
Notes:
Amortized O(1) for all operations. Each element moved at most twice. Space O(n).
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Use two stacks: push to stack1, pop/peek from stack2 (transfer when stack2 empty).
Example:
Input:
push(1), push(2), peek(), pop(), empty()Output:
[null, null, 1, 1, false]Common Mistakes:
- Transferring on every operation (amortized O(1) lost)
- Not checking if output stack is empty before transferring
- Duplicating transfer logic in pop and peek
- Wrong empty condition (must check both stacks)
Notes:
Amortized O(1) for all operations. Each element moved at most twice. Space O(n).
63/75
Implement Queue using Stacks