Skip to content

Commit

Permalink
Create 2025-01-12-Leetcode-225.md
Browse files Browse the repository at this point in the history
  • Loading branch information
hyeonukim committed Jan 13, 2025
1 parent 49f228d commit 902e5a1
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions _posts/2025-01-12-Leetcode-225.md
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)$

0 comments on commit 902e5a1

Please sign in to comment.