Skip to content

Completed both the code#2438

Open
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master
Open

Completed both the code#2438
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master

Conversation

@avcode3
Copy link

@avcode3 avcode3 commented Feb 5, 2026

No description provided.

@super30admin
Copy link
Owner

Strengths:

  • Your code is simple and easy to understand.
  • It correctly implements the FIFO behavior for the queue operations.

Areas for improvement:

  • The problem requires using two stacks to implement the queue. Your solution does not use any stacks; instead, it uses a list and directly manipulates it. You need to adhere to the problem constraints, which mandate using only standard stack operations (push to top, pop from top, peek from top, size, and is empty).
  • The pop operation in your solution has O(n) time complexity due to list slicing. This can be optimized by using two stacks as in the reference solution, which provides amortized O(1) time for pop and peek operations.
  • Consider using two stacks: one for input and one for output. When you need to pop or peek, if the output stack is empty, transfer all elements from the input stack to the output stack. This way, the elements are reversed in the output stack, and you can pop from the top of the output stack to get the front of the queue.

Here is how you can improve your solution:

class MyQueue:
    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def push(self, x: int) -> None:
        self.in_stack.append(x)

    def pop(self) -> int:
        self.peek()  # Ensure out_stack has the front element
        return self.out_stack.pop()

    def peek(self) -> int:
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack[-1]

    def empty(self) -> bool:
        return not self.in_stack and not self.out_stack

This approach uses two stacks and meets the problem requirements. The pop and peek operations are efficient due to the amortized constant time complexity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants