Hash Map / Set· 25 min

Determine if Two Strings Are Close

LeetCode #1657 · Medium · Interactive step-by-step visualization

Setup

Example inputword1 = "cabbba", word2 = "abbccc"
Step 1 / 4

Current step

1 / 4

Count both words. The allowed operations preserve the character set and only move frequencies between existing characters. word1 a:2 b:3 c:1; word2 a:1 b:2 c:3.

Step log

word1

c
0
a
1
b
2
b
3
b
4
a
5

word2

a
0
b
1
b
2
c
3
c
4
c
5

word1

a:2 b:3 c:1

word2

a:1 b:2 c:3

Active cursor
Comparing
Best or completed
Leaving or removed
determine-if-two-strings-are-close.java
1public boolean closeStrings(String word1, String word2) {
2 int[] first = count(word1), second = count(word2);
3 for (int i = 0; i < 26; i++)
4 if ((first[i] == 0) != (second[i] == 0)) return false;
5 Arrays.sort(first);
6 Arrays.sort(second);
7 return Arrays.equals(first, second);
8}
● Java
Time
O(n)
Space
O(1)
Pattern
hashing
Frames
4