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.