```python
def longest_common_subsequence(X, Y, m, n):
    """
    Finds the longest common subsequence of two sequences X and Y.

    Args:
        X: The first sequence.
        Y: The second sequence.
        m: The length of the first sequence.
        n: The length of the second sequence.

    Returns:
        The longest common subsequence. The return type is adapted to the
        input type (str, tuple, or list).
    """
    # dp_table[i][j] will store the length of the LCS of X[0...i-1] and Y[0...j-1].
    dp_table = [[0] * (n + 1) for _ in range(m + 1)]

    # Fill the DP table in a bottom-up manner.
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if X[i - 1] == Y[j - 1]:
                dp_table[i][j] = dp_table[i - 1][j - 1] + 1
            else:
                dp_table[i][j] = max(dp_table[i - 1][j], dp_table[i][j - 1])

    # Reconstruct the LCS by backtracking from the bottom-right corner.
    lcs_elements = []
    i, j = m, n
    while i > 0 and j > 0:
        # If the current elements match, they are part of the LCS.
        if X[i - 1] == Y[j - 1]:
            lcs_elements.append(X[i - 1])
            i -= 1
            j -= 1
        # If not, move in the direction of the longer subsequence.
        elif dp_table[i - 1][j] > dp_table[i][j - 1]:
            i -= 1
        else:
            j -= 1

    # The LCS is built in reverse order, so it needs to be reversed.
    lcs_elements.reverse()

    # Adapt the output type to the input type for common cases.
    if isinstance(X, str):
        return "".join(lcs_elements)
    if isinstance(X, tuple):
        return tuple(lcs_elements)
    
    return lcs_elements
```