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.