Implement Stack using Queues - Leetcode 225 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 7 ก.พ. 2025

ความคิดเห็น • 51

  • @hrvmhv4391
    @hrvmhv4391 3 ปีที่แล้ว +134

    As per the problem statement, you are only supposed to use valid queue operations i.e. push to back, peek/pop from front, size and is empty.
    So by that logic top() method is incorrect. If you write the for loop in push() then you can use peek() method in top().

    • @ishxnnn
      @ishxnnn ปีที่แล้ว +6

      You can also initialize a stacktop class variable to keep track of the top and just return that

    • @Rendis-p7z
      @Rendis-p7z ปีที่แล้ว +1

      Came here to say this also. Thanks for mentioning this.

    • @username0218-e2x
      @username0218-e2x 8 หลายเดือนก่อน +1

      Yeah this is a poor solution. Should be done using the basic FIFO queue module which doesn't allow half of what he's used.

    • @psuvlogs
      @psuvlogs 4 หลายเดือนก่อน

      front and back are valid operations for a queue. So getting the last element i.e. back is correct.

  • @flatmapper
    @flatmapper ปีที่แล้ว +6

    Leetcode says:
    "You must use only standard operations of a queue, which means that only `push to back`, `peek/pop from front`,`size` and `is empty` operations are valid."
    And here you used self.q[-1] which is accessing the last element which is not allowed

  • @Mykelboachie
    @Mykelboachie 3 ปีที่แล้ว +13

    Looks like you are starting to make these every day which is great news! Thank you

  • @green8026
    @green8026 ปีที่แล้ว +2

    I'm so glad you point out at the beginning that it would take O(n) to implement the pop operation. I was thinking to myself "that doesn't even make sense to use a queue, I'll have to iterate through the whole thing to pop the next stack item. (I literally was wracking my brain before watching the solution video about who I could possibly do that in O(1)).

  • @ngneerin
    @ngneerin 3 ปีที่แล้ว +34

    The reason leetcode is showing poor performance is that there are lot of people who have implemented it like a stack and not queue that behaves like stack

  • @jayeshvarma8382
    @jayeshvarma8382 ปีที่แล้ว +10

    Here, we are using deque funtionality in case of getting top element
    But we should use it as queue
    So we cannot directly get element from rear
    So it is wrong i think
    For that we should first perform operation like pop then we can get top element without popping

    • @sylvias-w9f
      @sylvias-w9f ปีที่แล้ว +1

      I came across the same question with you.There are some difference between queue and deque, so if we solve the problem by queue,the solution will be different.

  • @CodeShode
    @CodeShode 2 ปีที่แล้ว +5

    performance is relative, and many people have implemented it using stacks which pushes your solution towards the less efficient ones.

  • @blossombabalola1234
    @blossombabalola1234 2 ปีที่แล้ว +3

    This explanation is top tier. Thank you Neet

  • @aryamankukal1056
    @aryamankukal1056 6 หลายเดือนก่อน +2

    how are you allowed to use q[-1] if you need to use only queue operations

  • @Philgob
    @Philgob 4 หลายเดือนก่อน

    "You must use only standard operations of a queue, which means that only `push to back`, `peek/pop from front`,`size` and `is empty` operations are valid."
    And here you used self.q[-1] which is essentially peeking from the back which is not allowed
    Must get accepted because it's an easy but double queue solution is better

  • @CEOofTheHood
    @CEOofTheHood 3 ปีที่แล้ว +2

    Hi Mr.Neet, you have about covered most graph topic but one that seems to be missing is strongly connected components. Would really appreciate it if you could teach that when you have time.

  • @geghamayvazyan5637
    @geghamayvazyan5637 4 หลายเดือนก่อน

    javascript solution on neetcode pops with n^2 complexity as iterates through the array and removes element from the start causing other elements to shift left

  • @waseem_ibrahim
    @waseem_ibrahim ปีที่แล้ว +2

    For any one who is saying that the top() function is implemented properly, the idea behind using the index of [-1] as he did was that there is already a function for queues called "peek" that you could use that gives you the last element directly, so it is safe to say that it is implemented, and we always have an idea of what the top element would be.
    However, if anyone faces an issue in interview where the interviewer still wants an implementation for the top() function, you could make sure to keep O(1) for it by using a value that always tracks the top value, which would be always the last one pushed, or the 2nd to last one after popping
    Code Example:
    from collections import deque
    class MyStack:
    def __init__(self):
    self.q1 = deque()
    self.peek = None
    def push(self, x: int) -> None:
    self.q1.appendleft(x)
    self.peek = x
    def pop(self) -> int:
    n = len(self.q1)
    for i in range(n - 1):
    poped = self.q1.pop()
    self.q1.appendleft(poped)
    if i == n-2:
    self.peek = poped
    return self.q1.pop()
    def top(self) -> int:
    return self.peek
    def empty(self) -> bool:
    return len(self.q1) == 0

    • @pielily
      @pielily ปีที่แล้ว

      for queues, peek gets the first element, not the last. top is not implemented correctly here because you can't grab the last element like that w/ the constraints given in the problem

  • @PianoNumberOne
    @PianoNumberOne ปีที่แล้ว

    Excellent Solution, Easly Understood

  • @炒粿条-b1d
    @炒粿条-b1d 2 ปีที่แล้ว +3

    Dear Neet, can you teach us about 232. Implement Queue using Stacks as well? 232 is on the Grind 75 list

    • @fefefefefee32
      @fefefefefee32 2 ปีที่แล้ว

      th-cam.com/video/nPvjcQBplH4/w-d-xo.html

  • @ArpitJain_AJPlays
    @ArpitJain_AJPlays 3 ปีที่แล้ว +2

    Better to use queue, from queue import Queue. This makes more sense bcoz u r using deque and only implementing queue feature, so y not use queue. By the way nice explanation.

    • @gianniprocida3332
      @gianniprocida3332 2 ปีที่แล้ว +1

      Exactly. If you are going to use deque , you can remove from either side ( .popleft() and pop())

    • @nikhil_a01
      @nikhil_a01 2 ปีที่แล้ว +1

      Queue is a synchronized queue class for multithreaded programming. You can get away with it on LeetCode but it's not recommended for use as a general data structure because there's overhead for the synchronization.

  • @rahul-thakur
    @rahul-thakur 7 หลายเดือนก่อน

    Push is O(n), pop/top is O(1)

  • @MP-ny3ep
    @MP-ny3ep ปีที่แล้ว

    Amazing explanation

  • @rahulprasad2318
    @rahulprasad2318 3 ปีที่แล้ว +5

    If you know its length and are accessing it using -1 anyways then why not just use pop or return the -1 element and then do del q[-1]?

    • @nikhil_a01
      @nikhil_a01 2 ปีที่แล้ว +1

      Then you're using stack methods, so you're not implementing it using a queue. You're implementing a stack using a stack...
      NeetCode shouldn't be doing q[-1] because that's not a queue method. It's a mistake in the solution.

  • @HoratiuEugenVLAD
    @HoratiuEugenVLAD ปีที่แล้ว +3

    The top() could be implemented much simpler by reusing pop() and push()
    def push(self, x: int) -> None:
    self.q.append(x)
    def pop(self) -> int:
    for i in range(len(self.q) - 1):
    self.push(self.q.popleft())
    return self.q.popleft()
    def top(self) -> int:
    res = self.pop()
    self.push(res)
    return res

  • @vdyb745
    @vdyb745 2 ปีที่แล้ว

    Great explanation ! Tx !

  • @pichu8115
    @pichu8115 3 ปีที่แล้ว

    May i ask what app do you use to annotate in the video?

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +5

      Sure, I just use Paint3D

  • @ericndirangu5758
    @ericndirangu5758 3 ปีที่แล้ว

    When using two queues the runtime and space is over 70% ...strange

  • @pinpon163
    @pinpon163 2 ปีที่แล้ว

    Might be me, but I find this problem to be unnecessarily complex. It is not hard, but it is just annoying.

  • @LilJollyJoker
    @LilJollyJoker 10 หลายเดือนก่อน +1

    My Solution:
    class MyStack:
    def __init__(self):
    self.qStack = []
    self.qEmpty = []
    def push(self, x: int) -> None:
    self.qEmpty.append(x)
    for elem in self.qStack:
    self.qEmpty.append(elem)
    self.qStack = self.qEmpty
    self.qEmpty = []
    def pop(self) -> int:
    if len(self.qStack) > 0:
    return self.qStack.pop(0)
    def top(self) -> int:
    if len(self.qStack) > 0:
    return self.qStack[0]
    def empty(self) -> bool:
    return len(self.qStack) == 0

  • @rahul-thakur
    @rahul-thakur 7 หลายเดือนก่อน

    But, it's not using two stack.

  • @VaishnaviMamilla
    @VaishnaviMamilla ปีที่แล้ว

    if using dequeue we can simply use pop() right it will pop from rear abd behave as a stack why to use popleft

  • @TSS554
    @TSS554 11 หลายเดือนก่อน

    this problem is silly

  • @whiteheadiceprince1506
    @whiteheadiceprince1506 2 ปีที่แล้ว +1

    Maybe it's not efficient because you're using python and python in itself is... not efficient.

    • @nikhil_a01
      @nikhil_a01 2 ปีที่แล้ว +1

      If you use Python it only compares to other Python solutions. Mostly it's just randomness in the timing. When everyone does the same solution the timings get tightly clustered. I have almost the same solution and it's 40ms which is faster than 76% of solutions.
      Also some people are implementing it using a stack which is faster but not a correct solution. That messes up the timing for correct solutions.

  • @FaizanShaikh-zg9to
    @FaizanShaikh-zg9to 2 ปีที่แล้ว

    Hello can anyone please clarify if this a valid solution the time complexity is good and it beats 92% but just don't know if it is right way to do.
    class MyQueue:
    def __init__(self):
    self.num = []

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

    def pop(self) -> int:
    return self.num.pop(0)

    def peek(self) -> int:
    return self.num[0]

    def empty(self) -> bool:
    return len(self.num) == 0

  • @aakash4351
    @aakash4351 ปีที่แล้ว +1

    top operation is not legal.

  • @yashsrivastava677
    @yashsrivastava677 3 ปีที่แล้ว +1

    There is no solution for Leetcode 332 Reconstruct Itinerary. Please provide one.

  • @abhi_and_seki
    @abhi_and_seki 2 ปีที่แล้ว +2

    the solution is giving wrong answer @neet

  • @mahesh_kok
    @mahesh_kok 2 ปีที่แล้ว

    For pop when cant we just use self.q.popleft() thats it