Long Pressed Name
Problem
Given two strings name and typed, return true if typed could be a long-pressed version of name, otherwise return false.
- 1 ≤ name.length, typed.length ≤ 1000
- name and typed consist of only lowercase English letters.
Example
name = "alex", typed = "aaleex"trueThe typed string "aaleex" can be formed by long pressing the characters in "alex". For example, 'a' is pressed twice, 'l' once, 'e' twice, and 'x' once. The algorithm uses two pointers to traverse both strings simultaneously. At each step, it checks if the current characters match. If they do, both pointers advance. If they don't, it checks if the current typed character matches the previous typed character, indicating a long press, and advances only the typed pointer. If neither condition holds, the function returns false. The critical moment is when the typed character differs from the name character and the previous typed character, signaling an invalid long press.
Approach
Straightforward Solution
A brute-force approach might try to count consecutive characters in both strings and compare counts, but this requires extra bookkeeping and is more complex to implement.
Core Observation
The fundamental truth is that typed must be a supersequence of name where each character in name appears in order, possibly repeated multiple times consecutively in typed.
Path to Optimal
The key insight is to use two pointers to traverse both strings simultaneously. When characters match, advance both pointers. When they don't, check if the typed character is a repetition of the previous typed character (long press). If yes, advance typed pointer only. Otherwise, return false immediately. This approach efficiently validates the long press condition in a single pass.
Optimal Approach
Use two pointers i and j for name and typed respectively. Iterate through typed with j. If name[i] == typed[j], advance both. Else if typed[j] == typed[j-1], advance j only (long press). Else return false. After the loop, check if all characters in name were matched (i == len(name)). This guarantees O(n) time and O(1) space.
Time
O(n)
Each pointer advances at most the length of its respective string, resulting in a single linear pass through typed.
Space
O(1)
Only a fixed number of variables (two pointers and counters) are used, with no additional data structures proportional to input size.
Pattern Spotlight
Two Pointers (Greedy Validation)
When validating a sequence against a pattern with possible repeated characters, use two pointers to greedily match characters and allow the second pointer to advance on repeated characters, ensuring linear time verification without extra space.
Solution
| 1 | class Solution: |
| 2 | def isLongPressedName(self, name: str, typed: str) -> bool: |
| 3 | i = 0 |
| 4 | j = 0 |
| 5 | |
| 6 | while j < len(typed): |
| 7 | if i < len(name) and name[i] == typed[j]: |
| 8 | i += 1 |
| 9 | j += 1 |
| 10 | elif j > 0 and typed[j] == typed[j - 1]: |
| 11 | j += 1 |
| 12 | else: |
| 13 | return False |
| 14 | |
| 15 | return i == len(name) |
Step-by-Step Solution
Initialize Two Pointers for Name and Typed Strings
| 3 | i = 0 |
| 4 | j = 0 |
Objective
To set up indices to traverse both strings from the start.
Key Insight
Two pointers allow simultaneous traversal of name and typed, enabling direct comparison of characters and efficient detection of long press repetitions without extra space or preprocessing.
Interview Quick-Check
Core Logic
Using two pointers i and j to track positions in name and typed respectively is the foundation for linear-time validation.
State & Boundaries
Both pointers start at 0, representing the beginning of each string.
Traverse Typed String to Validate Long Pressed Characters
| 6 | while j < len(typed): |
| 7 | if i < len(name) and name[i] == typed[j]: |
| 8 | i += 1 |
| 9 | j += 1 |
| 10 | elif j > 0 and typed[j] == typed[j - 1]: |
| 11 | j += 1 |
| 12 | else: |
| 13 | return False |
Objective
To iterate through typed and verify it matches name with allowed long presses.
Key Insight
The traversal uses a greedy approach: if characters match, advance both pointers; if typed character repeats the previous typed character, advance typed pointer only; otherwise, the typed string is invalid. This logic efficiently handles all valid long press scenarios in a single pass.
Interview Quick-Check
Core Logic
The algorithm checks three conditions in order: exact character match, repeated typed character (long press), and invalid mismatch, ensuring correctness and efficiency.
Common Pitfalls & Bugs
Failing to check the previous typed character before advancing the typed pointer can cause incorrect acceptance of invalid strings.
State & Boundaries
The loop continues until the typed pointer reaches the end of typed.
Confirm Complete Match of Name After Traversal
| 15 | return i == len(name) |
Objective
To verify that all characters in name have been matched by the end of typed traversal.
Key Insight
Even if typed is fully traversed, the name pointer must have reached the end to confirm that typed contains all characters of name in order. This final check ensures no characters in name were skipped or unmatched.
Interview Quick-Check
Core Logic
Returning true only if i == len(name) guarantees that every character in name was matched in typed.
Line Analysis
This solution has 4 Critical lines interviewers watch for.
else:
Handle invalid character mismatch by returning false.
This immediate rejection upon mismatch is essential to prevent false positives, ensuring the algorithm only accepts typed strings that strictly follow the long press rules.
if i < len(name) and name[i] == typed[j]:
Check if current characters in name and typed match and i is within name bounds.
This condition is the core correctness check that advances both pointers only when characters align, ensuring the typed string follows the name sequence.
elif j > 0 and typed[j] == typed[j - 1]:
Check if current typed character equals previous typed character (long press scenario).
This check is critical to distinguish valid long presses from invalid mismatches, enabling the algorithm to accept repeated characters in typed that correspond to a single character in name.
return i == len(name)
Return true if all characters in name were matched; otherwise false.
This final check guarantees completeness of the match, preventing acceptance of typed strings that omit characters from name.
i = 0
Initialize pointer i to track position in name.
Pointer i marks the current character in name to be matched, enabling sequential verification against typed.
j = 0
Initialize pointer j to track position in typed.
Pointer j marks the current character in typed being examined, allowing traversal and comparison with name.
i += 1
Advance pointer i in name after a successful character match.
Moving i forward tracks progress through name, ensuring all characters are matched in order.
j += 1
Advance pointer j in typed after a successful character match.
Moving j forward continues traversal of typed, maintaining synchronization with name when characters match.
j += 1
Advance pointer j in typed when a long press repetition is detected.
Advancing j alone skips repeated characters in typed, correctly modeling long press behavior without advancing name pointer.
while j < len(typed):
Start loop to traverse typed while j is within bounds.
The loop ensures every character in typed is examined exactly once, enabling linear-time validation.
return False
End of while loop block.
Marks the end of the main validation loop that processes typed characters.
Test Your Understanding
Why must the algorithm check if the current typed character equals the previous typed character when it doesn't match the current name character?
Because a long press means characters in typed can be repeated consecutively. If the current typed character differs from the current name character but matches the previous typed character, it indicates a valid long press repetition rather than a mismatch.
Related Problems
Two Pointers pattern
Don't just read it. Drill it.
Reconstruct Long Pressed Name from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Long Pressed Name drill