"""Week 8: Stacks and queues, plus the monotonic stack pattern."""
from __future__ import annotations

from typing import List, Optional


class Stack:
    def __init__(self):
        self._items: List = []

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

    def pop(self):
        if not self._items:
            raise IndexError("pop from empty stack")
        return self._items.pop()

    def peek(self):
        if not self._items:
            raise IndexError("peek at empty stack")
        return self._items[-1]

    def __len__(self) -> int:
        return len(self._items)


class QueueWithTwoStacks:
    """Amortised O(1): move items to the out-stack only when it is empty."""

    def __init__(self):
        self._in: List = []
        self._out: List = []

    def enqueue(self, x) -> None:
        self._in.append(x)

    def dequeue(self):
        if not self._out:
            while self._in:
                self._out.append(self._in.pop())
        if not self._out:
            raise IndexError("dequeue from empty queue")
        return self._out.pop()

    def __len__(self) -> int:
        return len(self._in) + len(self._out)


class CircularQueue:
    """Fixed-capacity ring buffer: head index + count, wrap with modulo."""

    def __init__(self, capacity: int):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self._data: List[Optional[object]] = [None] * capacity
        self._head = 0
        self._count = 0

    def enqueue(self, x) -> bool:
        if self.is_full():
            return False
        self._data[(self._head + self._count) % len(self._data)] = x
        self._count += 1
        return True

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        x = self._data[self._head]
        self._data[self._head] = None
        self._head = (self._head + 1) % len(self._data)
        self._count -= 1
        return x

    def is_empty(self) -> bool:
        return self._count == 0

    def is_full(self) -> bool:
        return self._count == len(self._data)


def balanced_brackets(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack: List[str] = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack


def next_greater(nums: List[int]) -> List[int]:
    """For each element, the next larger value to its right, or -1. O(n) with a decreasing stack."""
    out = [-1] * len(nums)
    stack: List[int] = []
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            out[stack.pop()] = x
        stack.append(i)
    return out


def evaluate_postfix(tokens: List[str]) -> float:
    stack: List[float] = []
    ops = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b, "/": lambda a, b: a / b}
    for tok in tokens:
        if tok in ops:
            b, a = stack.pop(), stack.pop()
            stack.append(ops[tok](a, b))
        else:
            stack.append(float(tok))
    if len(stack) != 1:
        raise ValueError("malformed expression")
    return stack[0]


def infix_to_postfix(expression: str) -> List[str]:
    """Shunting-yard for + - * / and parentheses on space-separated or single-char tokens."""
    precedence = {"+": 1, "-": 1, "*": 2, "/": 2}
    output: List[str] = []
    ops: List[str] = []
    tokens = expression.replace("(", " ( ").replace(")", " ) ").split()
    for tok in tokens:
        if tok in precedence:
            while ops and ops[-1] != "(" and precedence[ops[-1]] >= precedence[tok]:
                output.append(ops.pop())
            ops.append(tok)
        elif tok == "(":
            ops.append(tok)
        elif tok == ")":
            while ops[-1] != "(":
                output.append(ops.pop())
            ops.pop()
        else:
            output.append(tok)
    while ops:
        output.append(ops.pop())
    return output
