"""Radix tree (path-compressed byte trie) mapping bytes keys to int values.

Node layout: every node is a plain Python list (fast to build and to index
with constant subscripts in CPython):

    node[0]  label   bytes   edge label from the parent (b"" for the root)
    node[1]  value   int or None (None: no key ends at this node)
    node[2]  count   int     number of keys stored in this subtree
    node[3]  kb      bytes / bytearray: first byte of each child's label,
                     sorted ascending (b"" for a node without children)
    node[4]  ch      list of child nodes, parallel to kb (() when none)

A child for byte c is found with kb.find(c) (memchr over at most 256 sorted
bytes); its label is then checked with key.startswith(label, depth).
"""

from bisect import bisect_left

_EMPTY_KB = b""
_EMPTY_CH = ()


class RadixTree:
    __slots__ = ("_root",)

    def __init__(self):
        self._root = [b"", None, 0, _EMPTY_KB, _EMPTY_CH]

    # ------------------------------------------------------------ lookups

    def get(self, key):
        node = self._root
        n = len(key)
        d = 0
        while d < n:
            i = node[3].find(key[d])
            if i < 0:
                return None
            node = node[4][i]
            lab = node[0]
            if not key.startswith(lab, d):
                return None
            d += len(lab)
        return node[1]

    def longest_prefix(self, key):
        node = self._root
        bv = node[1]
        bl = 0
        n = len(key)
        d = 0
        while d < n:
            i = node[3].find(key[d])
            if i < 0:
                break
            node = node[4][i]
            lab = node[0]
            if not key.startswith(lab, d):
                break
            d += len(lab)
            v = node[1]
            if v is not None:
                bv = v
                bl = d
        if bv is None:
            return None
        return (bl, bv)

    def prefix_count(self, prefix):
        node = self._root
        n = len(prefix)
        d = 0
        while d < n:
            i = node[3].find(prefix[d])
            if i < 0:
                return 0
            node = node[4][i]
            lab = node[0]
            if prefix.startswith(lab, d):
                d += len(lab)
                continue
            # The prefix may end inside this label.
            if len(lab) > n - d and lab.startswith(prefix[d:]):
                return node[2]
            return 0
        return node[2]

    def prefix_values(self, prefix, limit):
        out = []
        if limit <= 0:
            return out
        node = self._root
        n = len(prefix)
        d = 0
        while d < n:
            i = node[3].find(prefix[d])
            if i < 0:
                return out
            node = node[4][i]
            lab = node[0]
            if prefix.startswith(lab, d):
                d += len(lab)
                continue
            if len(lab) > n - d and lab.startswith(prefix[d:]):
                break
            return out
        cnt = node[2]
        if cnt == 0:
            return out
        app = out.append
        stack = [node]
        pop = stack.pop
        ext = stack.extend
        if limit >= cnt:
            # The whole subtree is wanted: pre-order walk without limit checks.
            while stack:
                nd = pop()
                v = nd[1]
                if v is not None:
                    app(v)
                ch = nd[4]
                if ch:
                    ext(reversed(ch))
            return out
        rem = limit
        while stack:
            nd = pop()
            v = nd[1]
            if v is not None:
                app(v)
                rem -= 1
                if not rem:
                    break
            ch = nd[4]
            if ch:
                ext(reversed(ch))
        return out

    def __len__(self):
        return self._root[2]

    # ------------------------------------------------------------ updates

    def insert(self, key, value):
        root = node = self._root
        n = len(key)
        d = 0
        # Subtree counts are incremented optimistically on the way down and
        # rolled back if the key turns out to be present already.
        node[2] += 1
        while d < n:
            c = key[d]
            kb = node[3]
            i = kb.find(c)
            if i < 0:
                leaf = [key[d:], value, 1, _EMPTY_KB, _EMPTY_CH]
                if kb:
                    pos = bisect_left(kb, c)
                    kb.insert(pos, c)
                    node[4].insert(pos, leaf)
                else:
                    node[3] = bytearray((c,))
                    node[4] = [leaf]
                return True
            ch = node[4]
            child = ch[i]
            lab = child[0]
            if key.startswith(lab, d):
                child[2] += 1
                node = child
                d += len(lab)
                continue
            # Split the edge to child after the common prefix of length j.
            ll = len(lab)
            m = n - d
            if ll < m:
                m = ll
            j = 1
            while j < m and lab[j] == key[d + j]:
                j += 1
            child[0] = lab[j:]
            b = lab[j]
            if d + j == n:
                # The key ends inside the label: the new middle node holds it.
                ch[i] = [lab[:j], value, child[2] + 1, bytearray((b,)), [child]]
                return True
            kc = key[d + j]
            leaf = [key[d + j:], value, 1, _EMPTY_KB, _EMPTY_CH]
            if kc < b:
                ch[i] = [lab[:j], None, child[2] + 1,
                         bytearray((kc, b)), [leaf, child]]
            else:
                ch[i] = [lab[:j], None, child[2] + 1,
                         bytearray((b, kc)), [child, leaf]]
            return True
        if node[1] is None:
            node[1] = value
            return True
        node[1] = value
        # Present already: undo the count increments along the full path.
        nd = root
        nd[2] -= 1
        d = 0
        while d < n:
            nd = nd[4][nd[3].find(key[d])]
            nd[2] -= 1
            d += len(nd[0])
        return False

    def remove(self, key):
        root = node = self._root
        parent = None
        pi = gi = 0
        n = len(key)
        d = 0
        # Counts are decremented optimistically and restored on a miss.
        node[2] -= 1
        while d < n:
            i = node[3].find(key[d])
            if i < 0:
                self._undo_remove(key, node)
                return False
            child = node[4][i]
            lab = child[0]
            if not key.startswith(lab, d):
                self._undo_remove(key, node)
                return False
            child[2] -= 1
            gp = parent
            gi = pi
            parent = node
            pi = i
            node = child
            d += len(lab)
        if node[1] is None:
            self._undo_remove(key, node)
            return False
        node[1] = None
        if parent is None:
            return True  # the root (empty key)
        ch = node[4]
        k = len(ch)
        if k == 0:
            # Delete the leaf from its parent.
            del parent[3][pi]
            pch = parent[4]
            del pch[pi]
            if parent is not root and parent[1] is None and len(pch) == 1:
                # Parent is left with no key and one child: merge them.
                c = pch[0]
                c[0] = parent[0] + c[0]
                gp[4][gi] = c
        elif k == 1:
            c = ch[0]
            c[0] = node[0] + c[0]
            parent[4][pi] = c
        return True

    def _undo_remove(self, key, stop):
        nd = self._root
        nd[2] += 1
        d = 0
        while nd is not stop:
            nd = nd[4][nd[3].find(key[d])]
            nd[2] += 1
            d += len(nd[0])

    # ------------------------------------------------------------ shape

    def node_count(self):
        total = 0
        stack = [self._root]
        while stack:
            nd = stack.pop()
            total += 1
            ch = nd[4]
            if ch:
                stack.extend(ch)
        return total

    def height(self):
        best = 0
        stack = [(self._root, 0)]
        while stack:
            nd, h = stack.pop()
            if h > best:
                best = h
            ch = nd[4]
            if ch:
                h += 1
                for c in ch:
                    stack.append((c, h))
        return best
