Long Pressed Name

The problem requires us to check if the string typed could be formed from the string name by possibly long pressing some keys. A key is long pressed if it is repeated one or more times consecutively.

Approach:

  1. Initialize Pointers: We will initialize two pointers, one for each string.
  2. Iterate Through Strings: We will iterate through both strings using the pointers, checking if the characters match.
  3. Handle Long Pressed Characters: If a character in typed is the same as the previous character, we need to check if it matches the current character in name. If not, it could be a long-pressed character.
  4. Final Check: We should ensure that we have checked all characters in name and handled the long-pressed characters in typed.

Code:

Here’s the code implementing the above approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        i, j = 0, 0 # Pointers for name and typed

        while j < len(typed):
            # If characters match, move both pointers
            if i < len(name) and name[i] == typed[j]:
                i += 1
            # If current character in typed is same as previous, it's a long press; else, return False
            elif j > 0 and typed[j] == typed[j - 1]:
                pass
            else:
                return False
            j += 1

        # Ensure all characters in name have been checked
        return i == len(name)

Explanation:

  • The while loop iterates through typed, and the pointers i and j are used to traverse name and typed, respectively.
  • If the characters at the current pointers match, both pointers are moved forward.
  • If the current character in typed is the same as the previous character but doesn’t match the current character in name, it’s considered a long press, and only the pointer in typed is moved forward.
  • If a character in typed doesn’t meet any of the above conditions, it means typed cannot be formed from name, and False is returned.
  • After the loop, we ensure that all characters in name have been checked.

Example:

  • For name = "alex" and typed = "aaleex", the function returns True, as ‘a’ and ’e’ are long pressed.
  • For name = "saeed" and typed = "ssaaedd", the function returns False, as there is no second ’e’ in the typed string.

This code takes care of the constraints and efficiently checks if the typed string could have been formed from the name string by long pressing some keys.