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.