Python 0925.py
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
regex = ""
for i in range(len(name)):
regex += name[i]
if i + 1 == len(name) or name[i] != name[i + 1]:
regex += "+" # repeated character in name
return re.search("^" + regex + "$", typed)
Difficulty
and has an acceptance rate of about 32% (400k+ submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “long-pressed name” problem by translating the original name into a regular-expression pattern that captures the allowed repetitions of each character. The pattern is then anchored at both the start (^) and end ($) of the string and applied to the typed input using Python’s re.search. If the pattern matches the whole typed string, the function returns a truthy value indicating that typed could be produced by long-pressing keys while typing name.
Key Steps
Constructing the base pattern
The algorithm iterates over the characters of name and appends each character to a growing pattern string.
regex = ""
for i in range(len(name)):
regex += name[i]
# ...
During this pass the code decides whether the current character may appear multiple times in typed.
Adding the repetition qualifier
When the current character is the last one in name or it differs from the next character, a '+' quantifier is appended. The '+' tells the regular-expression engine that the preceding character must appear at least once and may be repeated arbitrarily many times, which directly models the long-press behavior.
if i + 1 == len(name) or name[i] != name[i + 1]:
regex += "+" # repeated character in name
Because the '+' is added only after the final occurrence of a run of identical characters, the pattern correctly groups consecutive identical letters together.
Anchoring and matching
After the loop finishes, the pattern is wrapped with start-of-string (^) and end-of-string ($) anchors, guaranteeing that the entire typed string must conform to the constructed pattern. The anchored pattern is then passed to re.search.
return re.search("^" + regex + "$", typed)
If the search succeeds, the returned match object evaluates to True; otherwise it evaluates to False.
Edge Cases Handled
When name consists of a single character, the loop runs once, appends that character, and immediately adds a '+'. The resulting pattern ^a+$ matches any non-empty sequence of that character, covering the case where the user long-pressed the sole key.
If name contains consecutive identical characters, such as "aa", the loop adds the first 'a' without a '+' because the next character is the same. When the loop reaches the second 'a', the condition i + 1 == len(name) or name[i] != name[i + 1] becomes true, so a '+' is appended after the second 'a'. The final pattern ^aa+$ forces at least two 'a' characters, matching the required minimum count while still allowing extra repetitions.
An empty name results in an empty regex string. The final pattern becomes ^^$, which matches only an empty typed string. Thus the function correctly returns True when both inputs are empty and False otherwise.
When typed contains characters not present in name or appears in a different order, the anchored regular expression fails to match, and the function returns False. This covers mismatched ordering and extraneous characters.
Performance Optimizations
The algorithm builds the regular-expression pattern in a single linear pass over name. By appending characters directly to the regex string, it avoids the overhead of intermediate data structures such as lists or temporary strings for each character group.
Anchoring the pattern (^ and $) ensures that the regular-expression engine can reject non-conforming typed strings early, without needing to scan the entire input for partial matches.
Leveraging the built-in re module delegates the actual matching work to a highly optimized C implementation, which typically outperforms a pure-Python character-by-character comparison for this specific pattern shape.
Overall, the approach achieves the desired functionality with minimal explicit control flow and relies on the efficiency of the underlying regex engine for the heavy lifting.
ELI5 - Simplified Explanation
Imagine you are typing your name on a keyboard, but sometimes your finger gets stuck and you press a letter a few extra times. This code is like a little detective that checks if something you typed is just your name with some accidental extra letters added in.
The detective looks at your name one letter at a time to see how many times each part should appear. It creates a special pattern that says you need at least one of each letter in the right order. Because your finger might have stayed on the key for a bit too long, the pattern allows for those extra repeated letters.
Once the pattern is ready, the detective looks at what was fully typed out. It checks if the typed version follows the exact same order as your name while making sure that any extra letters only happen when they are just being held down longer than usual. If everything matches up according to these rules, the detective knows the typing was correct.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 859: Buddy Strings
- problem 914: X of a Kind in a Deck of Cards
- problem 1346: Check If N and Its Double Exist
- problem 1805: Number of Different Integers in a String
- problem 1909: Remove One Element to Make the Array Strictly Increasing
- problem 2047: Number of Valid Words in a Sentence
- problem 2469: Convert the Temperature
- problem 2525: Categorize Box According to Criteria
- problem 2591: Distribute Money to Maximum Children
- problem 2614: Prime In Diagonal
- problem 2660: Determine the Winner of a Bowling Game
- problem 2760: Longest Even Odd Subarray With Threshold
- problem 2765: Longest Alternating Subarray
- problem 1255: Maximum Score Words Formed by Letters
- problem 2251: Number of Flowers in Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality