LeetCode Entry
859. Buddy Strings
Is it just one swap s[i]<>s[j] to string s == string goal
859. Buddy Strings easy
blog post
substack

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/264
Problem TLDR
Is it just one swap s[i]<>s[j] to string s == string goal
Intuition
Compare two strings for each position. There are must be only two not equal positions and they must be mirrored pairs.
Approach
Let’s write it in Kotlin collections API style.
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
fun buddyStrings(s: String, goal: String): Boolean = s.length == goal.length && (
s == goal && s.groupBy { it }.any { it.value.size > 1 } ||
s.zip(goal)
.filter { (a, b) -> a != b }
.windowed(2)
.map { (ab, cd) -> listOf(ab, cd.second to cd.first) }
.let { it.size == 1 && it[0][0] == it[0][1] }
)