"""Stage 5: Stack and Monotonic Stack (problems 35-43)."""
from __future__ import annotations

from typing import List


def is_valid_parentheses(s: str) -> bool:
    """LC 20. Push openers; every closer must match the top."""
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack


class MinStack:
    """LC 155. Store (value, min so far) pairs so getMin is O(1)."""

    def __init__(self) -> None:
        self.stack: List[tuple] = []

    def push(self, val: int) -> None:
        current = min(val, self.stack[-1][1]) if self.stack else val
        self.stack.append((val, current))

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]


def eval_rpn(tokens: List[str]) -> int:
    """LC 150. Operands on a stack; division truncates toward zero."""
    stack: List[int] = []
    for tok in tokens:
        if tok in "+-*/" and len(tok) == 1:
            b, a = stack.pop(), stack.pop()
            if tok == "+":
                stack.append(a + b)
            elif tok == "-":
                stack.append(a - b)
            elif tok == "*":
                stack.append(a * b)
            else:
                stack.append(int(a / b))
        else:
            stack.append(int(tok))
    return stack[0]


def daily_temperatures(temperatures: List[int]) -> List[int]:
    """LC 739. Monotonic decreasing stack of indices still waiting for a warmer day."""
    out = [0] * len(temperatures)
    stack: List[int] = []
    for i, t in enumerate(temperatures):
        while stack and temperatures[stack[-1]] < t:
            j = stack.pop()
            out[j] = i - j
        stack.append(i)
    return out


def car_fleet(target: int, position: List[int], speed: List[int]) -> int:
    """LC 853. Sort by position descending; a car that arrives no later than the fleet ahead joins it."""
    fleets = 0
    slowest = 0.0
    for pos, spd in sorted(zip(position, speed), reverse=True):
        arrival = (target - pos) / spd
        if arrival > slowest:
            fleets += 1
            slowest = arrival
    return fleets


def largest_rectangle_area(heights: List[int]) -> int:
    """LC 84. Increasing stack; when a bar is popped, the current index is its right boundary."""
    stack: List[int] = []
    best = 0
    for i, h in enumerate(heights + [0]):
        while stack and heights[stack[-1]] >= h:
            height = heights[stack.pop()]
            left = stack[-1] + 1 if stack else 0
            best = max(best, height * (i - left))
        stack.append(i)
    return best


def next_greater_element(nums1: List[int], nums2: List[int]) -> List[int]:
    """LC 496. Precompute next greater for every value in nums2 with a monotonic stack."""
    nxt = {}
    stack: List[int] = []
    for x in nums2:
        while stack and stack[-1] < x:
            nxt[stack.pop()] = x
        stack.append(x)
    return [nxt.get(x, -1) for x in nums1]


def decode_string(s: str) -> str:
    """LC 394. On '[' push (current string, repeat count); on ']' pop and expand."""
    stack = []
    current, num = "", 0
    for ch in s:
        if ch.isdigit():
            num = num * 10 + int(ch)
        elif ch == "[":
            stack.append((current, num))
            current, num = "", 0
        elif ch == "]":
            prev, times = stack.pop()
            current = prev + current * times
        else:
            current += ch
    return current


def simplify_path(path: str) -> str:
    """LC 71. Split on '/', treat '..' as pop and skip '' and '.'."""
    stack: List[str] = []
    for part in path.split("/"):
        if part == "..":
            if stack:
                stack.pop()
        elif part and part != ".":
            stack.append(part)
    return "/" + "/".join(stack)
