"""Longest common subsequence (LCS).

Idea
----
``dp[i][j]`` is the LCS length of ``a[:i]`` and ``b[:j]``. If the last
characters match, extend the diagonal: ``dp[i-1][j-1] + 1``. Otherwise drop
one character from either string and keep the better result. Walking back
through the table from the bottom-right corner recovers one actual LCS.

Complexity
----------
Time:  O(m * n)
Space: O(m * n) (O(min(m, n)) is possible if you only need the length)

Used by
-------
``diff`` tools, DNA alignment, and version-control merges.
"""


def lcs(a: str, b: str) -> str:
    """Return one longest common subsequence of ``a`` and ``b``."""
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    out: list[str] = []
    i, j = m, n
    while i and j:
        if a[i - 1] == b[j - 1]:
            out.append(a[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return "".join(reversed(out))
