Determine if Two Strings Are Close (LeetCode 1657): Solution and Explanation

Medium
Hash table
String
Sorting
Counting

Two words are close if swaps of characters and whole-letter relabels can turn one into the other. Decide whether word1 and word2 are close.

Intuition

Rather than search through sequences of operations, ask what the operations can never change. Whatever survives every operation must match between the two words, and if all of it matches, the operations should be able to do the rest.

Swapping two characters only reorders the word. So position never matters, and only how many times each letter appears is left. Neither operation adds or removes characters, so the lengths must match too.

Relabeling exchanges two letters that are already present. It can move a count from one letter to another, but it cannot introduce a new letter or remove one. So the set of letters used is fixed, while which letter carries which count is free. What survives is the multiset of counts: sort each word's counts and compare.

Those conditions are also sufficient: relabel letters one pair at a time so each count lands on the right letter, then swap characters into the right order.

Approach: Letter sets plus sorted counts

  1. If len(word1) != len(word2), return false.
  2. Count each of the 26 letters in both words.
  3. For every letter, if it appears in one word but not in the other, return false.
  4. Sort both count arrays and return whether they are equal.

Step-by-step example

word1 = "cabbba", word2 = "abbccc"
  1. Both words have length 6, so continue.
  2. Counts for word1: a = 2, b = 3, c = 1. Counts for word2: a = 1, b = 2, c = 3.
  3. Both words use exactly the letters a, b and c, so the sets match.
  4. Sorted counts: word1 gives [3, 2, 1] and word2 gives [3, 2, 1]. They are equal.
  5. Return true: relabel so the letter with 3 copies matches, then swap characters into place.

Code: Python, Java, C++

1class Solution:
2    def closeStrings(self, word1: str, word2: str) -> bool:
3        if len(word1) != len(word2):
4            return False
5        c1 = [0] * 26
6        c2 = [0] * 26
7        for ch in word1:
8            c1[ord(ch) - 97] += 1
9        for ch in word2:
10            c2[ord(ch) - 97] += 1
11        for i in range(26):
12            if (c1[i] == 0) != (c2[i] == 0):
13                return False
14        return sorted(c1) == sorted(c2)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Letter sets plus sorted counts O(n)
Bitmask for the letter set O(n)
Hash maps and Counter O(n + k log k)
Time

O(n)

Counting reads each character once. The set check and the sort work on 26 numbers, which is constant.

Space

O(1)

Two arrays of 26 counts, independent of the input length.

Other approaches

Hash maps and Counter (time O(n + k log k), space O(k))

Build Counter(word1) and Counter(word2), compare their key sets, then compare sorted(values()) (or a counter of the counts). Same idea, shorter in Python, and it works for any alphabet.

Bitmask for the letter set (time O(n), space O(1))

Record each word's letters as a 26-bit mask and compare the masks instead of looping over letters. It is a small constant-factor change; the counts still need sorting.

Common mistakes

  • Comparing only the sorted counts. "aab" and "ccd" both have counts [2, 1] but use different letters, and relabeling cannot invent a letter, so they are not close.
  • Comparing only the letter sets. "aabbcc" and "aaabbc" use the same letters but have counts [2, 2, 2] versus [3, 2, 1].
  • Comparing count arrays per letter without sorting, which ignores what relabeling allows and rejects "cabbba" versus "abbccc".
  • Forgetting the length check. The later checks catch it, but returning early is cheaper and makes the reasoning explicit.

Frequently asked questions

Why is matching counts enough? Do I need to find the operations?

No. If the letter sets and sorted counts match, you can always relabel letters pair by pair so every letter has the right count, and then swaps can arrange the characters in any order. The question only asks whether it is possible.

Does sorting make it O(n log n)?

No. Only 26 counts are sorted, so that step is constant time. The overall cost is the O(n) counting pass.

Is the length check really needed?

Logically no, because equal sorted counts already imply equal lengths. It is a cheap early exit that also documents the first invariant.

What is the time and space complexity?

O(n) time and O(1) extra space for the two 26-entry count arrays.