LeetCode Entry

1657. Determine if Two Strings Are Close

14.01.2024 medium 2024 kotlin

Are strings convertible by swapping existing chars positions or frequencies.

1657. Determine if Two Strings Are Close medium blog post substack youtube image.png

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()