"""Python 3 solutions for problems marked "Solution included" in the README.

Standard library only. Each function names the LeetCode problem it solves.
"""
from __future__ import annotations

import heapq
import random
from bisect import bisect_left
from collections import deque
from itertools import accumulate


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right


# 680. Valid Palindrome II
def valid_palindrome_ii(s):
    def is_pal(i, j):
        while i < j:
            if s[i] != s[j]:
                return False
            i, j = i + 1, j - 1
        return True

    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return is_pal(i + 1, j) or is_pal(i, j - 1)
        i, j = i + 1, j - 1
    return True


# 1249. Minimum Remove to Make Valid Parentheses
def min_remove_to_make_valid(s):
    drop, stack = set(), []
    for i, ch in enumerate(s):
        if ch == "(":
            stack.append(i)
        elif ch == ")":
            if stack:
                stack.pop()
            else:
                drop.add(i)
    drop.update(stack)
    return "".join(ch for i, ch in enumerate(s) if i not in drop)


# 227. Basic Calculator II
def calculate(s):
    stack, num, op = [], 0, "+"
    for i, ch in enumerate(s + "+"):
        if ch.isdigit():
            num = num * 10 + int(ch)
        elif ch in "+-*/":
            if op == "+":
                stack.append(num)
            elif op == "-":
                stack.append(-num)
            elif op == "*":
                stack.append(stack.pop() * num)
            else:
                stack.append(int(stack.pop() / num))  # truncate toward zero
            op, num = ch, 0
    return sum(stack)


# 71. Simplify Path
def simplify_path(path):
    stack = []
    for part in path.split("/"):
        if part == "..":
            if stack:
                stack.pop()
        elif part and part != ".":
            stack.append(part)
    return "/" + "/".join(stack)


# 560. Subarray Sum Equals K
def subarray_sum(nums, k):
    counts, total, ans = {0: 1}, 0, 0
    for x in nums:
        total += x
        ans += counts.get(total - k, 0)
        counts[total] = counts.get(total, 0) + 1
    return ans


# 528. Random Pick with Weight
class RandomPickWeight:
    def __init__(self, w, rng=None):
        self.prefix = list(accumulate(w))
        self.rng = rng or random.Random()

    def pickIndex(self):
        target = self.rng.randint(1, self.prefix[-1])
        return bisect_left(self.prefix, target)


# 50. Pow(x, n)
def my_pow(x, n):
    if n < 0:
        x, n = 1 / x, -n
    result = 1.0
    while n:
        if n & 1:
            result *= x
        x *= x
        n >>= 1
    return result


# 199. Binary Tree Right Side View
def right_side_view(root):
    view, queue = [], deque([root] if root else [])
    while queue:
        view.append(queue[-1].val)
        for _ in range(len(queue)):
            node = queue.popleft()
            queue.extend(c for c in (node.left, node.right) if c)
    return view


# 200. Number of Islands
def num_islands(grid):
    grid = [row[:] for row in grid]
    rows, cols, count = len(grid), len(grid[0]) if grid else 0, 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                count += 1
                grid[r][c] = "0"
                stack = [(r, c)]
                while stack:
                    i, j = stack.pop()
                    for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                        if 0 <= ni < rows and 0 <= nj < cols and grid[ni][nj] == "1":
                            grid[ni][nj] = "0"
                            stack.append((ni, nj))
    return count


# 215. Kth Largest Element in an Array
def find_kth_largest(nums, k):
    heap = nums[:k]
    heapq.heapify(heap)
    for x in nums[k:]:
        if x > heap[0]:
            heapq.heapreplace(heap, x)
    return heap[0]


# 56. Merge Intervals
def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged
