Long Pressed Name - 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 friend's name, with some characters (possibly none) being long pressed.

Input & Output

Example 1 — Basic Long Press
$ Input: name = "alex", typed = "aaleex"
Output: true
💡 Note: The 'a' and 'e' were long pressed, resulting in extra characters, but the sequence matches the name
Example 2 — Wrong Character
$ Input: name = "saeed", typed = "ssaaedd"
Output: false
💡 Note: The 'e' in typed was long pressed, but we're missing one 'e' that should appear after 'a'
Example 3 — Perfect Match
$ Input: name = "leelee", typed = "lleeelee"
Output: true
💡 Note: All characters match with some long presses on 'l' and 'e'

Constraints

  • 1 ≤ name.length ≤ 1000
  • 1 ≤ typed.length ≤ 1000
  • name and typed consist of only lowercase English letters

Visualization

Tap to expand
Long Pressed Name - Optimal Solution INPUT name = "alex" a i=0 l i=1 e i=2 x i=3 typed = "aaleex" a j=0 a j=1 l j=2 e j=3 e j=4 x j=5 Two Pointers: i --> name index j --> typed index ALGORITHM STEPS 1 Initialize Pointers Set i=0, j=0 for both strings 2 Match Characters If name[i]==typed[j]: i++, j++ 3 Handle Long Press If typed[j]==typed[j-1]: j++ 4 Validate Result Return i == name.length Trace: a-a OK, skip a l-l OK e-e OK, skip e x-x OK i=4, name done! FINAL RESULT true OK All characters in name were matched in typed. Final State: i = 4 (name.length) j = 6 (typed.length) Key Insight: Use two pointers to traverse both strings simultaneously. When characters match, advance both pointers. When they don't match, check if it's a repeated character from a long press (typed[j] == typed[j-1]). Time: O(n+m) | Space: O(1) - Single pass through both strings with constant extra space. TutorialsPoint - Long Pressed Name | Two Pointer Approach
Asked in
Google 15 Facebook 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen