Implement Queue using Stacks
LeetCode 232 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Make push expensive so the oldest item stays on top.
मैंने Implement Queue using Stacks (LeetCode 232) ऐसे हल किया — Stack / Queue Design पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Keep stackOne ordered so its top is always the front of the queue. To push, pour everything into stackTwo, put the new item at the bottom of stackOne, and pour everything back on top. Then pop and peek are just the top of stackOne.
Approach
- 1
push: move stackOne → stackTwo, push x, move everything back.
- 2
pop: pop stackOne.
- 3
peek: read stackOne's top.
- 4
empty: stackOne has no items.
मैंने कैसे हल किया
Costly pushPythonO(n) push
class MyQueue:
def __init__(self):
self.stackOne = []
self.stackTwo = []
def push(self, x):
while self.stackOne:
self.stackTwo.append(self.stackOne.pop())
self.stackOne.append(x)
while self.stackTwo:
self.stackOne.append(self.stackTwo.pop())
def pop(self):
if not self.stackOne:
return False
return self.stackOne.pop()
def peek(self):
return self.stackOne[-1]
def empty(self):
return len(self.stackOne) == 0Implement Queue using Stacks — अक्सर पूछे जाने वाले प्रश्न
Implement Queue using Stacks के पीछे intuition क्या है?
Keep stackOne ordered so its top is always the front of the queue. To push, pour everything into stackTwo, put the new item at the bottom of stackOne, and pour everything back on top. Then pop and peek are just the top of stackOne.
Implement Queue using Stacks (LeetCode 232) कैसे हल करें?
1. push: move stackOne → stackTwo, push x, move everything back. 2. pop: pop stackOne. 3. peek: read stackOne's top. 4. empty: stackOne has no items.
Implement Queue using Stacks की time और space complexity क्या है?
Time: O(n) push, O(1) pop/peek। Space: O(n)। (Accepted approach: Costly push।)
Implement Queue using Stacks में आम गलतियाँ क्या हैं?
The amortised two-stack version makes pop O(1) amortised instead.