Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Long Pressed Name

Updated
2 min read

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 name string and one for the typed string.
  • 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 typed matches the previous character in typed, it implies a long press; advance the typed pointer only.
  • Early Exit Conditions: If at any point the characters don't match and a long press cannot be justified, return False. Also return False if 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 name and m is the length of typed. 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)

More from this blog

C

Chatmagic blog

2894 posts