Long Pressed Name

Decide whether a typed string could be a name typed with some keys held down too long.

Your friend is typing your name on a keyboard. Sometimes a key is held down too long, and its character is typed one or more extra times. This is called a long press. You are given name and the string your friend actually typed, typed. Return true if typed could be name with some keys long pressed, and false otherwise.

Example 1
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: the a and the e were long pressed.
Example 2
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: name needs two e's in a row, but typed has only one.
Solution

The Idea

You have probably held a key a moment too long and seen "helllo" on the screen. Here your friend types "alex", and the screen shows "aaleex". Could that come from typing "alex" with a few keys held down?

Look at the picture below. The top row is name and the bottom row is typed. Read typed from left to right. The first a is the a of the name, so a line joins them. The second a repeats the a typed just before it, so it is a long press. Then l and e match the next letters of the name, the second e is another long press, and x matches the x.

The name alex above the typed string aaleex. Lines join the typed a, l, e and x to the a, l, e and x of the name. The second a and the second e of typed are marked long press.

Every letter of the name got a line, in order, and every other typed character is a long press. So the answer for Example 1 is true.

Example 2 goes wrong partway. The name is "saeed" and typed is "ssaaedd". The first s matches, the second s is a long press, the a matches, the second a is a long press, and the e matches the first e of "saeed". The next typed character is d, but the name still needs its second e. The d is not that e, and it does not repeat the e typed before it. No held key can turn into a d, so the answer is false.

So each typed character must be one of two things: the next letter of the name still to be typed, or a repeat of the character typed just before it. Anything else is a wrong key. How do we check that without guessing which characters are long presses?

Keep one marker in each string and move both from left to right. The marker in typed moves on every character, and the marker in name moves only when a letter is matched. Walking through two strings with one marker each is a form of the two-pointer technique. In many two-pointer problems the markers start at opposite ends and walk toward each other. Here both start at the left and move forward, at different speeds.

Solution Approach

Turning that idea into code means settling three things: what the two markers hold, which test to try first on each typed character, and how to treat the first character and the end of typed.

The two markers

What should each marker hold? i is the position of the next letter of name that still has to be typed, and j is the position of the character of typed being read. j moves on every step, and i moves only on a match. Each character is looked at once, so there is no need to cut the strings into pieces or try different splits.

Matching before skipping

What if a typed character is both the next letter of the name and a repeat of the character before it? Take the name "leelee" typed as "lleeelee". After l, a long press of l and the first e, the next typed e could be the second e of the name or a long press of the first.

The right choice is the match. A letter of the name has to be typed at some point, while a long press is optional. A version that tests for a repeat first counts every e after the first as a long press. The name's second e is never matched, and that version returns false for this input. So the match test comes first.

The first character and the end of typed

Is there a character that cannot be a long press? The first character of typed has nothing before it, so it must match the first letter of the name. For the name "a" typed as "ba", the b is a wrong key straight away.

And when typed runs out, is the answer always true? Only if the whole name was typed, which means i reached the end of name. For "alex" typed as "aale", every typed character is fine, but the x was never typed.

Java Solution

The method isLongPressedName works in these steps:

  1. First, set i to 0, the position of the next letter of name still to be typed.
  2. Read typed with a for loop, moving j from the first character to the last, and keep the current character in c.
  3. If i is still inside name and name.charAt(i) equals c, it is a match: move i forward.
  4. Otherwise, if j is 0 or c differs from the previous typed character, typed.charAt(j - 1), it is a wrong key: return false. If neither holds, c is a long press, and the loop just moves on.
  5. After the loop, return whether i equals name.length(), that is, whether every letter of the name was typed.

The main method runs both examples, the "leelee" case, an extra a after the x, a string that stops before the x, a wrong first key, and an exact typing.

Java
public class LongPressedName {

    public static boolean isLongPressedName(String name, String typed) {
        int i = 0;                            // next character of name to match
        for (int j = 0; j < typed.length(); j++) {
            char c = typed.charAt(j);
            if (i < name.length() && name.charAt(i) == c) {
                i++;                          // matches the next intended character
            } else if (j == 0 || c != typed.charAt(j - 1)) {
                return false;                 // not a match and not a repeat: a wrong key
            }
            // otherwise c repeats the previous typed character: a long press, skip it
        }
        return i == name.length();            // every character of name was typed
    }

    public static void main(String[] args) {
        System.out.println(isLongPressedName("alex", "aaleex"));
        System.out.println(isLongPressedName("saeed", "ssaaedd"));
        System.out.println(isLongPressedName("leelee", "lleeelee"));
        System.out.println(isLongPressedName("alex", "aaleexa"));
        System.out.println(isLongPressedName("alex", "aale"));
        System.out.println(isLongPressedName("a", "ba"));
        System.out.println(isLongPressedName("alex", "alex"));
    }
}

Running it prints:

Output
true
false
true
false
false
false
true

The true on the first line is "aaleex" from Example 1, and the false below it is "ssaaedd", which stops at the d. Look at the third line: "lleeelee" gives true because the match test comes first, so the second e of "leelee" is matched instead of skipped.

The fourth line is false for "aaleexa". After the x, i is already past the end of the name, and the last a neither matches nor repeats the x. The fifth line, "aale", is false only because of the final check: the loop ends with i still on the x. Returning true after the loop instead would accept this input.

The sixth line is "ba", rejected at its first character by the j == 0 test. Without that test, typed.charAt(j - 1) would ask for position -1 and throw a StringIndexOutOfBoundsException. The last line shows that a name typed exactly, with no long press at all, is true too.

Complexity

The loop reads typed once and does a fixed amount of work for each character.

  • Time: O(n), where n is the length of typed. Each step compares at most two pairs of characters, and i moves forward at most once per step, so name adds no extra passes.
  • Space: O(1). The method keeps two positions and one char, and never copies or splits the strings.

Is Subsequence walks through two strings with one marker each in the same way.