#1657
Determine if Two Strings Are Close
MediumHash TableStringSortingCountingHash MapCounting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages frequency counts of characters and their occurrences. By ensuring that both strings have the same unique characters and the same frequency distribution, we can determine if they are close without generating permutations.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in both strings.
- 2Step 2: Check if both strings have the same set of unique characters.
- 3Step 3: Check if the frequency counts can be rearranged to match each other.
solution.py6 lines
1from collections import Counter
2
3def areClose(word1, word2):
4 if len(word1) != len(word2): return False
5 count1, count2 = Counter(word1), Counter(word2)
6 return sorted(count1.values()) == sorted(count2.values()) and set(count1.keys()) == set(count2.keys())ℹ
Complexity note: The time complexity is O(n) because we traverse each string once to count character frequencies. The space complexity is O(n) due to the storage of frequency counts.
- 1Both strings must have the same unique characters to be close.
- 2The frequency of characters must be rearrangeable to match between the two strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.