LeetCode Entry
1657. Determine if Two Strings Are Close
Are strings convertible by swapping existing chars positions or frequencies.
1657. Determine if Two Strings Are Close medium
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/471
Problem TLDR
Are strings convertible by swapping existing chars positions or frequencies.
Intuition
By the problem definition, we must compare the frequencies numbers. Also, sets of chars must be equal.
Approach
Let’s use some Kotlin’s API:
- groupingBy
- eachCount
- run
- sorted
Complexity
-
Time complexity: \(O(n)\), as we are sorting only 26 elements
-
Space complexity: \(O(n)\)
Code
fun String.f() = groupingBy { it }.eachCount()
.run { keys to values.sorted() }
fun closeStrings(word1: String, word2: String) =
word1.f() == word2.f()