Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Buddy Strings

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "859" 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 two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal. Example 2: Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal. Example 3: Input: s = "aa", goal = "aa" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal. Constraints: 1 <= s.length, goal.length <= 2 * 104 s and goal consist of lowercase letters.

Explanation

Here's the breakdown:

  • High-Level Approach:

    • First, check if the lengths of the two strings are equal. If not, they cannot be made equal by swapping.
    • Next, identify the indices where the characters in s and goal differ. If there are exactly two such indices, check if swapping the characters at those indices in s makes it equal to goal.
    • If the strings are identical, check if there are duplicate characters in s. If there are, then swapping them won't change the string and will make the two strings the same. Otherwise, return false.
  • Complexity:

    • Runtime: O(n), where n is the length of the strings. Storage: O(1) - constant extra space.

Code

    def buddyStrings(s: str, goal: str) -> bool:
    if len(s) != len(goal):
        return False

    if s == goal:
        seen = set()
        for char in s:
            if char in seen:
                return True
            seen.add(char)
        return False

    diff_indices = []
    for i in range(len(s)):
        if s[i] != goal[i]:
            diff_indices.append(i)

    if len(diff_indices) == 2:
        i, j = diff_indices[0], diff_indices[1]
        return s[i] == goal[j] and s[j] == goal[i]

    return False

More from this blog

C

Chatmagic blog

2894 posts