#2531
Make Number of Distinct Characters Equal
MediumHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all pairs, we can analyze the distinct character counts and determine if a swap can balance them. By counting the frequency of characters, we can derive the conditions under which a swap would equalize the distinct counts.
⚙️
Algorithm
5 steps- 1Step 1: Count the distinct characters in both strings using frequency arrays.
- 2Step 2: Calculate the distinct counts for word1 and word2.
- 3Step 3: If the absolute difference between the distinct counts is greater than 2, return false (impossible to balance with one swap).
- 4Step 4: If the counts are equal or differ by 1, return true (one swap can balance them).
- 5Step 5: If they differ by 2, check if there exists a character in word1 that can be swapped with a character in word2.
solution.py9 lines
1def canMakeDistinctEqual(word1, word2):
2 from collections import Counter
3 count1 = Counter(word1)
4 count2 = Counter(word2)
5 distinct1 = len(count1)
6 distinct2 = len(count2)
7 if abs(distinct1 - distinct2) > 2:
8 return False
9 return distinct1 == distinct2 or abs(distinct1 - distinct2) == 1 or (distinct1 - distinct2 == 2 and any(c in count2 for c in count1)) or (distinct2 - distinct1 == 2 and any(c in count1 for c in count2))ℹ
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 space required for the frequency maps.
- 1Understanding the distinct character counts is crucial for solving the problem efficiently.
- 2A single swap can only balance the distinct counts if they differ by 0, 1, or 2.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.