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.