Problem 925

Abstract / Summary

Given two names, determine if the second name could be a long pressed version of the first by checking extra characters are repeats of existing ones and order is preserved.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
9 lines | 343 bytes | submitted October 11, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 32% (400k+ submissions).

Typical patterns to solve this problem:
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.62 | σ = 1.82

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
33 links | 19 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

16 solutions   October 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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