LeetCode solutions

2615. Make Number of Distinct Characters Equal

My accepted Python solution to LeetCode problem 2615, Make Number of Distinct Characters Equal, running in 63ms.

  • Difficulty: Medium
  • Python
  • Runtime 63ms
  • Memory 18MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 63ms, memory 18MB, accepted 2025-12-30.

python
class Solution:
    def isItPossible(self, word1: str, word2: str) -> bool:
        from collections import Counter
        
        c1 = Counter(word1)
        c2 = Counter(word2)
        
        # Try all possible swaps
        for ch1 in c1:
            for ch2 in c2:
                # Simulate swap: remove ch1 from word1, add ch2 to word1
                #                remove ch2 from word2, add ch1 to word2
                
                # Calculate new distinct counts
                d1 = len(c1)
                d2 = len(c2)
                
                # Effect on word1: remove ch1, add ch2
                if ch1 == ch2:
                    # No change in distinct counts
                    new_d1 = d1
                    new_d2 = d2
                else:
                    # word1 loses ch1 (if count becomes 0) and gains ch2 (if not already there)
                    new_d1 = d1
                    if c1[ch1] == 1:  # removing last occurrence
                        new_d1 -= 1
                    if ch2 not in c1:  # adding new char
                        new_d1 += 1
                    
                    # word2 loses ch2 (if count becomes 0) and gains ch1 (if not already there)
                    new_d2 = d2
                    if c2[ch2] == 1:
                        new_d2 -= 1
                    if ch1 not in c2:
                        new_d2 += 1
                
                if new_d1 == new_d2:
                    return True
        
        return False

Source