Leetcode 859: Buddy Strings

grid47
grid47
Exploring patterns and algorithms
Aug 13, 2024 7 min read

You are given two strings, s and goal, consisting of lowercase letters. Your task is to determine whether you can swap exactly two characters in s so that the resulting string matches goal. If this is possible, return true, otherwise return false. The swap is defined as selecting two different indices i and j, and swapping the characters at those positions in s.
Problem
Approach
Steps
Complexity
Input: You are given two strings, s and goal, both consisting of lowercase letters.
Example: Input: s = "cd", goal = "dc"
Constraints:
• 1 <= s.length, goal.length <= 2 * 10^4
• s and goal consist of lowercase letters.
Output: Return true if it is possible to swap two characters in s such that the string becomes equal to goal. Otherwise, return false.
Example: Output: true
Constraints:
Goal: The goal is to determine if a valid swap exists such that s becomes goal.
Steps:
• Step 1: If the lengths of s and goal are different, return false.
• Step 2: Count how many positions differ between s and goal. If more than two positions differ, return false.
• Step 3: If there are exactly two positions where s and goal differ, check if swapping these two characters will make the strings equal.
• Step 4: If the strings are already identical, check if any character repeats in s, as swapping identical characters will not change the string.
Goal: The strings s and goal are guaranteed to follow the input constraints.
Steps:
• The lengths of s and goal are between 1 and 2 * 10^4.
• The strings s and goal consist only of lowercase English letters.
Assumptions:
• The input strings s and goal will always contain lowercase English letters.
• The input strings will always be of valid lengths and contain only alphabetic characters.
Input: Input: s = "xy", goal = "yx"
Explanation: In this example, we can swap the characters at indices 0 and 1 in s to get 'yx', which matches goal.

Input: Input: s = "xy", goal = "xy"
Explanation: In this example, s is already equal to goal, so the answer is false because no swap is necessary.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus