Implement Stack using Queues
LeetCode 225 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Rotate after each push so the newest is at the front.
আমি Implement Stack using Queues (LeetCode 225) এভাবে সমাধান করেছি — Stack / Queue Design প্যাটার্নের একটি সহজ প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.
Approach
- 1
push: enqueue x, then move the other n−1 elements behind it.
- 2
pop: dequeue the front.
- 3
top: peek the front.
- 4
empty: queue is empty.
আমি কীভাবে সমাধান করেছি
Single queue, rotate on pushPythonO(n) push
from collections import deque
class MyStack:
def __init__(self):
self.Q1 = deque()
self.Q2 = deque()
def push(self, x):
self.Q1.append(x)
for i in range(len(self.Q1) - 1):
self.Q1.append(self.Q1.popleft())
def pop(self):
if not self.Q1:
return None
return self.Q1.popleft()
def top(self):
if not self.Q1:
return None
return self.Q1[0]
def empty(self):
return len(self.Q1) == 0Implement Stack using Queues — সাধারণ প্রশ্ন
Implement Stack using Queues-এর পেছনে intuition কী?
A queue gives first-in-first-out, a stack needs last-in-first-out. After pushing a new element, rotate the queue (pop from the front and push to the back) n−1 times so the new element ends up at the front — then pop and top are just the queue's front.
Implement Stack using Queues (LeetCode 225) কীভাবে সমাধান করবেন?
1. push: enqueue x, then move the other n−1 elements behind it. 2. pop: dequeue the front. 3. top: peek the front. 4. empty: queue is empty.
Implement Stack using Queues-এর time আর space complexity কত?
Time: O(n) push, O(1) pop/top। Space: O(n)। (Accepted approach: Single queue, rotate on push।)
Implement Stack using Queues-এ সাধারণ ভুলগুলো কী?
One queue is enough; the two-queue version is commented out in the code.