Buddy Strings
Easy · Hash Table, String
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].
Example 1
Input: s = "ab", goal = "ba" Output: true
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
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
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.
Starter code (python)
class Solution(object):
def buddyStrings(self, s, goal):
"""
:type s: str
:type goal: str
:rtype: bool
"""
Related problems
- Two Sum (Easy)
- Longest Substring Without Repeating Characters (Medium)
- Longest Palindromic Substring (Medium)
Previous: Minimum Cost to Hire K Workers · Next: Lemonade Change · All problems
Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.