Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 232 · Stack / Queue Design

Implement Queue using Stacks

LeetCode 232 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Make push expensive so the oldest item stays on top.

எளிதுStackDesignQueue
LeetCode இல் திற ↗

நான் 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. 1

    push: move stackOne → stackTwo, push x, move everything back.

  2. 2

    pop: pop stackOne.

  3. 3

    peek: read stackOne's top.

  4. 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) == 0
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Implement 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.