"""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

from collections import Counter, OrderedDict, deque


class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next


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


# 206. Reverse Linked List
def reverse_list(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev


# 25. Reverse Nodes in k-Group
def reverse_k_group(head, k):
    node = head
    for _ in range(k):
        if not node:
            return head
        node = node.next
    prev, cur = reverse_k_group(node, k), head
    for _ in range(k):
        cur.next, prev, cur = prev, cur, cur.next
    return prev


# 8. String to Integer (atoi)
def my_atoi(s):
    i, n = 0, len(s)
    while i < n and s[i] == " ":
        i += 1
    sign = 1
    if i < n and s[i] in "+-":
        sign = -1 if s[i] == "-" else 1
        i += 1
    num = 0
    while i < n and s[i].isdigit():
        num = num * 10 + int(s[i])
        i += 1
    return max(-(2 ** 31), min(2 ** 31 - 1, sign * num))


# 168. Excel Sheet Column Title
def convert_to_title(n):
    out = []
    while n:
        n, r = divmod(n - 1, 26)
        out.append(chr(ord("A") + r))
    return "".join(reversed(out))


# 1647. Minimum Deletions to Make Character Frequencies Unique
def min_deletions(s):
    used, deletions = set(), 0
    for count in sorted(Counter(s).values(), reverse=True):
        while count and count in used:
            count -= 1
            deletions += 1
        used.add(count)
    return deletions


# 54. Spiral Matrix
def spiral_order(matrix):
    out = []
    top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
    while top <= bottom and left <= right:
        out += [matrix[top][c] for c in range(left, right + 1)]
        out += [matrix[r][right] for r in range(top + 1, bottom + 1)]
        if top < bottom and left < right:
            out += [matrix[bottom][c] for c in range(right - 1, left - 1, -1)]
            out += [matrix[r][left] for r in range(bottom - 1, top, -1)]
        top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
    return out


# 48. Rotate Image (in place, clockwise)
def rotate(matrix):
    n = len(matrix)
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:
        row.reverse()


# 98. Validate Binary Search Tree
def is_valid_bst(root, low=float("-inf"), high=float("inf")):
    if not root:
        return True
    if not low < root.val < high:
        return False
    return is_valid_bst(root.left, low, root.val) and is_valid_bst(root.right, root.val, high)


# 102. Binary Tree Level Order Traversal
def level_order(root):
    levels, queue = [], deque([root] if root else [])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            queue.extend(c for c in (node.left, node.right) if c)
        levels.append(level)
    return levels


# 146. LRU Cache
class LRUCache:
    def __init__(self, capacity):
        self.capacity, self.data = capacity, OrderedDict()

    def get(self, key):
        if key not in self.data:
            return -1
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)
