File: long-pressed-name/solution.py

Date: 2026-06-06

Time: 17:24

Long Pressed Name — long-pressed-name/solution.py

Purpose

Solves LeetCode 925: Long Pressed Name. Given a name string and a typed string, determines whether typed could have been produced by long-pressing keys while typing name — meaning each character in name appears in typed in order, and any extra characters in typed must be duplicates of the immediately preceding character.

Key Components

Solution.isLongPressedName(name, typed) -> bool — The core algorithm. Uses a two-pointer approach where i tracks position in name and j iterates over typed.

Three cases per character typed[j]:

1. Match: typed[j] == name[i] → advance i (consume a required character)

2. Long-press repeat: typed[j] == typed[j-1] → skip (it's a duplicate from holding the key)

3. Mismatch: anything else → return False immediately

After the loop, i == len(name) confirms every character in name was consumed.

TestLongPressedName — 11 unit tests covering the standard cases: basic long-press ("alex""aaleex"), identical strings, single-character edge cases, mismatched characters, shorter typed, empty typed, and trailing extra characters.

Patterns

Dependencies

Imports: unittest only — no project-internal dependencies.

Imported by: long-pressed-name/test_solution.py (the "Imported By" list in the prompt is the full cross-repo test suite that shares the same unittest import, not actual importers of this module's Solution class).

Flow


for each character in typed (index j):
    if it matches name[i]  →  advance i (greedy consume)
    elif it matches typed[j-1]  →  skip (long-press)
    else  →  return False

return whether all of name was consumed (i == len(name))

The j > 0 guard before typed[j] == typed[j-1] prevents an index-out-of-bounds on the first character. If typed[0] doesn't match name[0], it falls through to return False.

Invariants

Error Handling

No explicit error handling. The method assumes valid string inputs per LeetCode constraints. Empty typed with non-empty name returns False naturally (the loop body never executes, so i stays at 0).

Topics to Explore

Beliefs