Solving Leetcode Interviews in Seconds with AI: Long Pressed Name
Introduction
In this blog post, we will explore how to solve the LeetCode problem "925" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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.
Explanation
Here's a breakdown of the approach, followed by the Python code:
- Two-Pointer Approach: Use two pointers, one for the
namestring and one for thetypedstring. - Character Matching and Long Press Handling: Iterate through both strings. If characters match, advance both pointers. If characters don't match but the current character in
typedmatches the previous character intyped, it implies a long press; advance thetypedpointer only. Early Exit Conditions: If at any point the characters don't match and a long press cannot be justified, return
False. Also returnFalseif the name pointer reaches the end but there is still some characters left in typed which do not match the previous character in typed.Time Complexity: O(m + n), where n is the length of
nameand m is the length oftyped. Space Complexity: O(1).
Code
def isLongPressedName(name: str, typed: str) -> bool:
"""
Checks if the typed string is a potentially long pressed version of the name string.
"""
i, j = 0, 0
while j < len(typed):
if i < len(name) and name[i] == typed[j]:
i += 1
j += 1
elif j > 0 and typed[j] == typed[j - 1]:
j += 1
else:
return False
return i == len(name)