from typing import Optional


def collapse_polymer(poly: str, kill_symbol: Optional[str] = None) -> str:
    """Collapses the polymer by walking through the sting backwards, removing pairs.
    If the optional `kill_symbol` flag is used, any link in the chain using that symbol
    will also be removed.
    
    Arguments:
        poly {str} -- The polymber to be collapsed
    
    Keyword Arguments:
        kill_symbol {Optional[str]} -- A symbol that should be removed, 
                    even if it doesn't have a matching pair (default: {None})
    
    Returns:
        str -- The collapsed polymer
    """

    idx = -1
    _poly = list(poly)
    try:
        while "Scanning Polymer":
            c = _poly[idx]
            if kill_symbol is not None and c.upper() == kill_symbol.upper():
                _poly.pop(idx)
                idx += 1
            elif ((c == c.upper() and _poly[idx-1] == c.lower()) or
                (c == c.lower() and _poly[idx-1] == c.upper())):
                _poly.pop(idx)
                _poly.pop(idx)
                idx += 1
            else:
                idx -= 1
    except IndexError:
        pass
    return ''.join(_poly)