Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Reverse Prefix of Word

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2000" 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

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". Return the resulting string. Example 1: Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation: The first occurrence of "d" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". Example 2: Input: word = "xyxzxe", ch = "z" Output: "zxyxxe" Explanation: The first and only occurrence of "z" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". Example 3: Input: word = "abcd", ch = "z" Output: "abcd" Explanation: "z" does not exist in word. You should not do any reverse operation, the resulting string is "abcd". Constraints: 1 <= word.length <= 250 word consists of lowercase English letters. ch is a lowercase English letter.

Explanation

Here's a breakdown of the solution:

  • Find the Index: Locate the index of the first occurrence of the character ch within the string word. If ch is not found, return the original string.
  • Reverse the Segment: If ch is found, reverse the portion of the string from index 0 up to and including the index where ch was found.
  • Concatenate: Combine the reversed segment with the remaining part of the original string to form the final result.

  • Runtime Complexity: O(n) & Storage Complexity: O(n), where n is the length of the input string word.

Code

    def reverse_prefix(word: str, ch: str) -> str:
    """
    Reverses the prefix of a string up to the first occurrence of a character.

    Args:
        word: The input string.
        ch: The character to search for.

    Returns:
        The string with the reversed prefix, or the original string if the character is not found.
    """
    try:
        index = word.index(ch)
        prefix = word[:index + 1]
        reversed_prefix = prefix[::-1]
        return reversed_prefix + word[index + 1:]
    except ValueError:
        return word

More from this blog

C

Chatmagic blog

2894 posts