"""Exponential (galloping) search.

Idea
----
When the target is probably near the start, or the length is unknown, probe
indices 1, 2, 4, 8, ... until you overshoot the target, then binary-search
inside the last range. The cost depends on the target's position ``i``
rather than the total length.

Complexity
----------
Time:  O(log i), where i is the index of the target
Space: O(1)

When to use
-----------
Unbounded or very long sorted streams; it is also the "galloping" step in
Timsort's merge.
"""

from collections.abc import Sequence
from typing import Any


def exponential_search(items: Sequence[Any], target: Any) -> int:
    """Return an index of ``target`` in sorted ``items`` or -1."""
    n = len(items)
    if n == 0:
        return -1
    if items[0] == target:
        return 0
    bound = 1
    while bound < n and items[bound] < target:
        bound *= 2
    lo, hi = bound // 2, min(bound + 1, n)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo if lo < n and items[lo] == target else -1
