Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 225 · Stack / Queue Design

Implement Stack using Queues

LeetCode 225 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Rotate after each push so the newest is at the front.

ಸುಲಭStackDesignQueue
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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. 1

    push: enqueue x, then move the other n−1 elements behind it.

  2. 2

    pop: dequeue the front.

  3. 3

    top: peek the front.

  4. 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) == 0
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

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