#925
Long Pressed Name
EasyTwo PointersStringTwo PointersString Matching
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses two pointers to traverse both strings simultaneously, ensuring that we only move forward in 'typed' when we see a match or a valid long press. This is efficient and straightforward.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one for 'name' and one for 'typed'.
- 2Step 2: Traverse 'typed' while comparing it to 'name'.
- 3Step 3: If characters match, move both pointers forward.
- 4Step 4: If characters don't match, check if the current character in 'typed' is the same as the previous one (indicating a long press). If not, return False.
- 5Step 5: After the loop, ensure all characters in 'name' have been matched.
solution.py11 lines
1def isLongPressedName(name: str, typed: str) -> bool:
2 i, j = 0, 0
3 while j < len(typed):
4 if i < len(name) and name[i] == typed[j]:
5 i += 1
6 elif j > 0 and typed[j] == typed[j - 1]:
7 pass
8 else:
9 return False
10 j += 1
11 return i == len(name)ℹ
Complexity note: The optimal solution runs in O(n) time because we traverse each string only once, making it efficient for larger inputs.
- 1The order of characters in 'name' must be preserved in 'typed'.
- 2Long presses can only extend the sequence of the same character.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.