Talentd
FleetCode
Make and follow sheets.Sign in

Long Pressed Name solution and explanation

EasyStringTwo Pointers5 min read32.8% acceptanceUpdated 9 Apr 2026
Faulty Keyboard | long pressed name | Leetcode 925 Solution in HindiPepcoding · 17:40 · 64K viewsWatch on YouTube
9 more videos on this problem
  1. Faulty Keyboard | long pressed name | Leetcode 925 Solution in HindiPepcoding · 17:40 · 64K views
  2. LeetCode Long Pressed Name Solution Explained - JavaNick White · 7:30 · 8K views
  3. 925. Long Pressed Name | LEETCODE EASYcode Explainer · 10:27 · 974 views
  4. LeetCode 925 Long Pressed Name - Interesting String Interview Question Solved With 2 PointersAlgorithmicIQ · 15:33 · 627 views
  5. LeetCode Long Pressed Name Solution Explained - JavaCode Unraveled · 13:26 · 582 views
  6. Разбор задачи 925 leetcode.com Long Pressed Name. Решение на C++3.5 задачи в неделю · 11:42 · 548 views
  7. LeetCode 925 | Long Pressed Name | 2 Pointers | JavaSleepy Cracker · 6:04 · 538 views
  8. Leetcode 925. Long Pressed Name (Easy)The Leetcode Grind · 7:15 · 522 views
  9. Long Pressed Name | JAVA | LeetCodeKnowledge Amplifier · 12:14 · 401 views
  10. LeetCode 925 Solution in Java | Long Pressed Name | Arrays & Strings | DSA Placement Series SheetShivansh Pareek | Code Crunch · 14:03 · 268 views

The problem

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 was not in the typed output.

Constraints:

  • 1 <= name.length, typed.length <= 1000
  • name and typed consist of only lowercase English letters.

Approach overview

Problem Overview: You are given two strings: name and typed. The string typed represents what appears on the keyboard when someone types name, but some characters might be long‑pressed. A long press repeats the same character multiple times. The task is to verify whether typed could have been produced from name while preserving the character order.

Approach 1: Two Pointers Technique (O(n) time, O(1) space)

This is the optimal approach and the one interviewers expect. Use two pointers: one for name and one for typed. Iterate through typed while matching characters with name. When both pointers match, move both forward. If they don't match but the current typed character equals the previous character in typed, treat it as a long press and advance only the typed pointer. If neither condition holds, the string is invalid. This works because long presses only repeat the previous character without changing order. The scan runs once across the strings, giving O(n) time complexity with O(1) extra space.

This pattern is common in Two Pointers problems where two sequences must be compared while preserving order. Since you only track indices and a previous character check, the implementation stays simple and memory efficient.

Approach 2: Frequency Count Comparison (O(n) time, O(1) space)

Another way to reason about the problem is by grouping consecutive characters in both strings. For example, name = "alex" becomes groups like a(1), l(1), e(1), x(1). If typed = "aaleex", the groups are a(2), l(1), e(2), x(1). Iterate through both strings and count the length of each consecutive character block. For the strings to be valid, the characters must match and the count in typed must be greater than or equal to the count in name. If typed has fewer occurrences of a character than name, it means a required character was skipped.

This approach relies on basic String processing and run-length counting. Complexity remains O(n) because each character is processed once while forming groups. Space complexity stays O(1) since counts are tracked using simple variables.

Recommended for interviews: The Two Pointers solution is the expected answer. It demonstrates strong control over sequential comparison problems and minimal memory usage. The frequency group method is also valid but slightly more verbose. Showing the brute reasoning first (character repetition groups) and then optimizing to the pointer scan signals strong problem‑solving ability.

Approach 1: Two Pointers Technique

The two-pointer technique involves iterating through both the 'name' and 'typed' strings simultaneously. We use two indices, one for each string. The idea is to compare the characters between the two strings and verify if the characters in 'typed' match the characters in 'name'. If the character in 'name' matches the character in 'typed', move both pointers forward. If it's a long press (i.e., the current and previous 'typed' characters are the same), increment the 'typed' pointer. If the characters do not match and it's not a long press scenario, return false.

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        i = 0
        for j in range(len(typed)):
            if i < len(name) and name[i] == typed[j]:
                i += 1
            elif j == 0 or typed[j] != typed[j - 1]:
                return False
        return i == len(name)
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int i = 0, j = 0;
        while (j < typed.length()) {
            if (i < name.length() && name.charAt(i) == typed.charAt(j)) {
                i++;
            } else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1)) {
                return false;
            }
            j++;
        }
        return i == name.length();
    }
}
#include <string>
using namespace std;

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int i = 0, j = 0;
        while (j < typed.size()) {
            if (i < name.size() && name[i] == typed[j]) {
                i++;
            } else if (j == 0 || typed[j] != typed[j - 1]) {
                return false;
            }
            j++;
        }
        return i == name.size();
    }
};
var isLongPressedName = function(name, typed) {
    let i = 0, j = 0;
    while (j < typed.length) {
        if (i < name.length && name[i] === typed[j]) {
            i++;
        } else if (j === 0 || typed[j] !== typed[j - 1]) {
            return false;
        }
        j++;
    }
    return i === name.length;
};
#include <stdbool.h>
#include <string.h>

bool isLongPressedName(char *name, char *typed) {
    int i = 0, j = 0;
    while (j < strlen(typed)) {
        if (i < strlen(name) && name[i] == typed[j]) {
            i++;
        } else if (j == 0 || typed[j] != typed[j - 1]) {
            return false;
        }
        j++;
    }
    return i == strlen(name);
}
public class Solution {
    public bool IsLongPressedName(string name, string typed) {
        int i = 0, j = 0;
        while (j < typed.Length) {
            if (i < name.Length && name[i] == typed[j]) {
                i++;
            } else if (j == 0 || typed[j] != typed[j - 1]) {
                return false;
            }
            j++;
        }
        return i == name.Length;
    }
}

In Python, this solution leverages a for-loop with a pointer to track the position in 'name'. As it iterates over 'typed', it ensures each character can be justified by either a future 'name' character or a long press.

Complexity

Time Complexity: O(n + m)
Space Complexity: O(1)

Try this approach in the editor

Approach 2: Frequency Count Comparison

In this approach, we utilize frequency counting. We traverse both strings to collect segments of consecutive repeating characters. For each segment in 'name', ensure there is a corresponding segment in 'typed' with equal or greater length, indicating potential long presses.

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        i, j = 0, 0
        while i < len(name) and j < len(typed):
            if name[i] != typed[j]:
                return False
            countN = countT = 0
            current = name[i]
            while i < len(name) and name[i] == current:
                i += 1
                countN += 1
            while j < len(typed) and typed[j] == current:
                j += 1
                countT += 1
            if countN > countT:
                return False
        return i == len(name) and j == len(typed)
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int i = 0, j = 0;
        while (i < name.length() && j < typed.length()) {
            if (name.charAt(i) != typed.charAt(j)) return false;
            int countN = 0, countT = 0;
            char current = name.charAt(i);
            while (i < name.length() && name.charAt(i) == current) {
                i++;
                countN++;
            }
            while (j < typed.length() && typed.charAt(j) == current) {
                j++;
                countT++;
            }
            if (countN > countT) return false;
        }
        return i == name.length() && j == typed.length();
    }
}
#include <string>
using namespace std;

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int i = 0, j = 0;
        while (i < name.length() && j < typed.length()) {
            if (name[i] != typed[j]) return false;
            int nameCount = 0, typedCount = 0;
            char currentChar = name[i];
            while (i < name.length() && name[i] == currentChar) {
                i++;
                nameCount++;
            }
            while (j < typed.length() && typed[j] == currentChar) {
                j++;
                typedCount++;
            }
            if (nameCount > typedCount) return false;
        }
        return i == name.length() && j == typed.length();
    }
};
var isLongPressedName = function(name, typed) {
    let i = 0, j = 0;
    while (i < name.length && j < typed.length) {
        if (name[i] !== typed[j]) return false;
        let countN = 0, countT = 0;
        let current = name[i];
        while (i < name.length && name[i] === current) {
            i++;
            countN++;
        }
        while (j < typed.length && typed[j] === current) {
            j++;
            countT++;
        }
        if (countN > countT) return false;
    }
    return i === name.length && j === typed.length;
};
#include <stdbool.h>
#include <string.h>

bool checkSegment(char *name, char *typed) {
    int lenN = strlen(name);
    int lenT = strlen(typed);
    int i = 0, j = 0;
    while (i < lenN && j < lenT) {
        int countN = 0, countT = 0;
        char currentChar = name[i];
        while (i < lenN && name[i] == currentChar) {
            countN++;
            i++;
        }
        while (j < lenT && typed[j] == currentChar) {
            countT++;
            j++;
        }
        if (countN > countT) return false;
    }
    return i == lenN && j == lenT;
}

bool isLongPressedName(char *name, char *typed) {
    return checkSegment(name, typed);
}
public class Solution {
    public bool IsLongPressedName(string name, string typed) {
        int i = 0, j = 0;
        while (i < name.Length && j < typed.Length) {
            if (name[i] != typed[j]) return false;
            int nameCount = 0, typedCount = 0;
            char currentChar = name[i];
            while (i < name.Length && name[i] == currentChar) {
                i++;
                nameCount++;
            }
            while (j < typed.Length && typed[j] == currentChar) {
                j++;
                typedCount++;
            }
            if (nameCount > typedCount) return false;
        }
        return i == name.Length && j == typed.Length;
    }
}

This Python function implements segment matching and counting logic to ascertain if all characters in 'name' can be long pressed into 'typed'.

Complexity

Time Complexity: O(n + m)
Space Complexity: O(1)

Try this approach in the editor

Approach 3: Two Pointers

We use two pointers i and j to point to the first character of the strings typed and name respectively, and then start traversing. If typed[j] is not equal to name[i], it means the two strings do not match, and we directly return False. Otherwise, we find the next position of the continuous identical characters, denoted as x and y respectively. If x - i > y - j, it means the number of characters in typed is less than the number of characters in name, and we directly return False. Otherwise, we update i and j to x and y respectively, continue traversing, until i and j have traversed name and typed respectively, and return True.

The time complexity is O(m + n), where m and n are the lengths of the strings name and typed respectively. The space complexity is $O(1)`.

function isLongPressedName(name: string, typed: string): boolean {
    const [m, n] = [name.length, typed.length];
    let i = 0;
    let j = 0;
    while (i < m && j < n) {
        if (name[i] !== typed[j]) {
            return false;
        }
        let x = i + 1;
        while (x < m && name[x] === name[i]) {
            x++;
        }
        let y = j + 1;
        while (y < n && typed[y] === typed[j]) {
            y++;
        }
        if (x - i > y - j) {
            return false;
        }
        i = x;
        j = y;
    }
    return i === m && j === n;
}
func isLongPressedName(name string, typed string) bool {
	m, n := len(name), len(typed)
	i, j := 0, 0

	for i < m && j < n {
		if name[i] != typed[j] {
			return false
		}
		x, y := i+1, j+1

		for x < m && name[x] == name[i] {
			x++
		}

		for y < n && typed[y] == typed[j] {
			y++
		}

		if x-i > y-j {
			return false
		}

		i, j = x, y
	}

	return i == m && j == n
}
impl Solution {
    pub fn is_long_pressed_name(name: String, typed: String) -> bool {
        let (m, n) = (name.len(), typed.len());
        let (mut i, mut j) = (0, 0);
        let s: Vec<char> = name.chars().collect();
        let t: Vec<char> = typed.chars().collect();

        while i < m && j < n {
            if s[i] != t[j] {
                return false;
            }
            let mut x = i + 1;
            while x < m && s[x] == s[i] {
                x += 1;
            }
            let mut y = j + 1;
            while y < n && t[y] == t[j] {
                y += 1;
            }
            if x - i > y - j {
                return false;
            }
            i = x;
            j = y;
        }

        i == m && j == n
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Two Pointers Technique

Time Complexity: O(n + m)
Space Complexity: O(1)

Frequency Count Comparison

Time Complexity: O(n + m)
Space Complexity: O(1)

Two Pointers–

Complexity analysis

ApproachTimeSpaceWhen to Use
Two Pointers TechniqueO(n)O(1)Best general solution for comparing sequential strings with possible repeats
Frequency Count (Character Groups)O(n)O(1)Useful when reasoning about consecutive character blocks or explaining the long‑press rule clearly

Frequently asked questions

Is Long Pressed Name easy or hard?

LeetCode classifies Long Pressed Name as an Easy problem. The main challenge is correctly handling repeated characters in the typed string while ensuring no required characters from the name are skipped.

Long Pressed Name Python/Java solution

In Python or Java, implement the two-pointer scan across the name and typed strings. Compare characters, allow repeated characters in typed, and ensure the order is preserved. The logic is identical across languages and runs in O(n) time with constant space.

How to solve Long Pressed Name in O(n)?

Traverse the typed string with a pointer while comparing it with the name pointer. When characters match, advance both pointers. If the typed character equals the previous typed character, treat it as a long press and advance only the typed pointer. Any other mismatch means the typed string is invalid.

What is the best approach for Long Pressed Name?

The best approach is the Two Pointers technique. Use one pointer for the original name and another for the typed string. Move both pointers when characters match, and allow the typed pointer to move alone when it repeats the previous character. This runs in O(n) time and O(1) space.

Is Long Pressed Name asked at Google/Amazon/Meta?

This problem has appeared in interview preparation sets for companies like Google and Amazon because it tests string traversal and pointer control. While not extremely difficult, it checks whether you can reason about sequential constraints and repeated characters efficiently.

What data structure is used in Long Pressed Name?

The problem primarily uses string traversal with the Two Pointers technique. No advanced data structures are required. Some alternative explanations use counters to track consecutive character frequencies.

What is the time complexity of Long Pressed Name?

The optimal solution runs in O(n) time where n is the length of the typed string. Each character is processed at most once using two pointers. Space complexity is O(1) because only index variables and simple counters are used.

Comments

Now write it yourselfClose this page and solve Long Pressed Name in the editor, without looking.
Practise Long Pressed Name