Long Pressed Name Problem
Description
LeetCode Problem 925.
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
Example 1:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3:
Input: name = "leelee", typed = "lleeelee"
Output: true
Example 4:
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.
Constraints:
- 1 <= name.length <= 1000
- 1 <= typed.length <= 1000
- name and typed contain only lowercase English letters.
Solution
Approach: Two Pointers
Walk through typed one key press at a time, keeping a pointer i to the next character of name that still has to appear. Each press in typed can be only one of two things:
- the next character of the name: if
typed[j] == name[i], it matches, so advancei; - a long press: otherwise it must repeat the previous key,
typed[j] == typed[j - 1].
If a press is neither, typed contains a key the friend never meant to press, so return false. At the end, return whether i reached the end of name; a typed that stops early (like "alex" vs "aalle") leaves characters unmatched.
Checking the name first is safe: when a press could be both the name's next character and a long press, using it for the name never hurts, because any further copies of that key right after it still count as long presses. For name = "leelee", typed = "lleeelee", the second l is not the next character e, so it is a long press; the third e comes after the name has moved on to l, so it is a long press too.
Complexity: O(n) time and O(1) space, where n is the length of typed.
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
i = 0 # next character of name we still need to match
for j in range(len(typed)):
if i < len(name) and typed[j] == name[i]:
i += 1 # this key press types the next character of the name
elif j == 0 or typed[j] != typed[j - 1]:
return False # neither the next character nor a repeat of the last key
return i == len(name) # every character of the name must have been typed
Now write it from memory
Close the write-up and solve it yourself against the tests.