"""Week 16: Tries, bit manipulation and backtracking."""
from __future__ import annotations

from typing import Dict, List


class Trie:
    def __init__(self):
        self.root: Dict = {}
        self.END = "$"

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node[self.END] = True

    def _find(self, prefix: str):
        node = self.root
        for ch in prefix:
            node = node.get(ch)
            if node is None:
                return None
        return node

    def contains(self, word: str) -> bool:
        node = self._find(word)
        return node is not None and self.END in node

    def starts_with(self, prefix: str) -> bool:
        return self._find(prefix) is not None

    def words_with_prefix(self, prefix: str) -> List[str]:
        node = self._find(prefix)
        out: List[str] = []

        def walk(n: Dict, path: str) -> None:
            for key in sorted(n):
                if key == self.END:
                    out.append(path)
                else:
                    walk(n[key], path + key)

        if node is not None:
            walk(node, prefix)
        return out


def count_set_bits(n: int) -> int:
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count


def is_power_of_two(n: int) -> bool:
    return n > 0 and n & (n - 1) == 0


def single_number(nums: List[int]) -> int:
    out = 0
    for x in nums:
        out ^= x
    return out


def subsets_by_bitmask(items: List) -> List[List]:
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]


def n_queens_count(n: int) -> int:
    """Backtracking with bitmasks for columns and both diagonals."""
    full = (1 << n) - 1

    def place(cols: int, diag1: int, diag2: int) -> int:
        if cols == full:
            return 1
        total = 0
        free = full & ~(cols | diag1 | diag2)
        while free:
            bit = free & -free
            free -= bit
            total += place(cols | bit, ((diag1 | bit) << 1) & full, (diag2 | bit) >> 1)
        return total

    return place(0, 0, 0)


def combination_sum(candidates: List[int], target: int) -> List[List[int]]:
    candidates = sorted(set(candidates))
    out: List[List[int]] = []
    path: List[int] = []

    def go(start: int, remaining: int) -> None:
        if remaining == 0:
            out.append(path[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break
            path.append(candidates[i])
            go(i, remaining - candidates[i])
            path.pop()

    go(0, target)
    return out


def solve_sudoku(board: List[List[int]]) -> bool:
    """Fill zeros in a 9x9 board in place. Returns False if no solution exists."""
    rows = [set() for _ in range(9)]
    cols = [set() for _ in range(9)]
    boxes = [set() for _ in range(9)]
    empty = []
    for r in range(9):
        for c in range(9):
            v = board[r][c]
            if v:
                rows[r].add(v)
                cols[c].add(v)
                boxes[r // 3 * 3 + c // 3].add(v)
            else:
                empty.append((r, c))

    def fill(i: int) -> bool:
        if i == len(empty):
            return True
        r, c = empty[i]
        b = r // 3 * 3 + c // 3
        for v in range(1, 10):
            if v not in rows[r] and v not in cols[c] and v not in boxes[b]:
                board[r][c] = v
                rows[r].add(v)
                cols[c].add(v)
                boxes[b].add(v)
                if fill(i + 1):
                    return True
                rows[r].remove(v)
                cols[c].remove(v)
                boxes[b].remove(v)
                board[r][c] = 0
        return False

    return fill(0)
