generated from cotes2020/chirpy-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
--- | ||
title: Leetcode 225. Implement Stack using Queues | ||
description: Explanation for Leetcode 225 - Implement Stack using Queues, and its solution in Python. | ||
date: 2025-01-12 | ||
categories: [Leetcode, Stack, Easy] | ||
tags: [Leetcode, Python, Study, Stack, Easy] | ||
math: true | ||
--- | ||
|
||
## Problem | ||
[Leetcode 225 - Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/) | ||
|
||
Example: | ||
``` | ||
Input | ||
["MyStack", "push", "push", "top", "pop", "empty"] | ||
[[], [1], [2], [], [], []] | ||
Output | ||
[null, null, null, 2, 2, false] | ||
Explanation | ||
MyStack myStack = new MyStack(); | ||
myStack.push(1); | ||
myStack.push(2); | ||
myStack.top(); // return 2 | ||
myStack.pop(); // return 2 | ||
myStack.empty(); // return False | ||
``` | ||
|
||
## Approach | ||
|
||
Stack is LIFO (last element that gets added to list pops out first) | ||
|
||
Queue is FIFO (first element that gets added to list pops out first) | ||
|
||
Thus, if we wanted to implement Stack using Queue, we have to keep in mind that when we add we have to make sure that the added element is going to be popped out first. | ||
|
||
Here is the Python code for the solution: | ||
```python | ||
class myStack: | ||
def __init__(self): | ||
self.q = deque() | ||
|
||
def push(self, x: int) -> None: | ||
self.q.append(x) | ||
# because we want the element that gets added last to be popped out first we can shift the queue so 'x' is at the end. | ||
for _ in range(len(self.q)-1): | ||
self.q.append(self.q.popleft()) | ||
|
||
# we don't have to worry about popping since we rearranged the queue | ||
def pop(self) -> int: | ||
return self.q.popleft() | ||
|
||
# we don't have to worry about top since we rearranged the queue | ||
def top(self) -> int: | ||
return q[0] | ||
|
||
def empty(self) -> bool: | ||
return len(self.q) == 0 | ||
``` | ||
## Time Complexity and Space Complexity | ||
|
||
Time Complexity: $O(1)$ for each operation but push, push will cost $O(n)$ | ||
|
||
Space Complexity: $O(n)$ |