அல்கோரிதம்auxiliary stack

Auxiliary stack — இரண்டாவது property

TT
Testlaa Team
May 14, 20261 min read

இரண்டாவது stack sync — min/max O(1) queries.

Try this in Python

class MinStack:
    def __init__(self) -> None:
        self.data: list[int] = []
        self.mins: list[int] = []

    def push(self, x: int) -> None:
        self.data.append(x)
        self.mins.append(x if not self.mins else min(x, self.mins[-1]))

    def pop(self) -> None:
        self.data.pop()
        self.mins.pop()

    def min(self) -> int:
        return self.mins[-1]


ms = MinStack()
ms.push(3)
ms.push(1)
ms.push(2)
print(ms.min())
ms.pop()
print(ms.min())

Key takeaways

  • Aux — monotonic/min structure.
  • Max — max mirror.
  • Frequency — (value, count).

Tags:

Stacks & queuesPythonமாணவர்கள்