Determine if Two Strings Are Close in Python – LeetCode75 Explained

The Determine if Two Strings Are Close problem from LeetCode 75 is a popular string manipulation challenge that tests your ability to work with sets, character frequency counts and transformation logic. This problem often appears in coding interviews because it requires careful reasoning about when two strings can be considered “equivalent” under specific rules.

Determine if Two Strings Are Close in Python – LeetCode75 Explained

In this blog, we’ll walk through the problem statement, examples, and a step-by-step Python solution with explanations.

Problem Statement

You are given two strings, word1 and word2.

Two strings are considered close if you can apply the following operations any number of times:

  1. Swap any two existing characters.
  2. Transform every occurrence of one character into another existing character, and do the same for the transformed one.

Return True if word1 and word2 are close, otherwise return False.

Understanding the Problem

At first, this might sound tricky, but the logic is straightforward:

  • Both strings must be the same length, otherwise transformation is impossible.
  • Both must use the same set of characters because you can’t transform into a character that doesn’t exist in the other word.
  • The frequency counts of characters (when sorted) must match. This ensures the transformations align properly.

In short: same characters + same frequency distribution = strings are close.

Examples

Example 1

Input:

word1 = "abc"
word2 = "bca"

Output:

True

Explanation: Both strings use {a, b, c} and each character appears once.

Example 2

Input:

word1 = "a"
word2 = "aa"

Output:

False

Explanation: Lengths differ, so they can’t be transformed.

Example 3

Input:

word1 = "cabbba"
word2 = "abbccc"

Output:

True

Explanation:

  • Both use {a, b, c}.
  • Frequencies are [1, 2, 3] in both (after sorting).
    So transformation is possible.

Python Solution – Step by Step

Here’s a clean Python implementation:

from collections import Counter

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        # Step 1: Compare lengths
        if len(word1) != len(word2):
            return False
        
        # Step 2: Compare character sets
        if set(word1) != set(word2):
            return False
        
        # Step 3: Compare frequency counts
        count1 = Counter(word1)
        count2 = Counter(word2)
        
        return sorted(count1.values()) == sorted(count2.values())

Step 1: Compare Lengths

If lengths differ, return False immediately.

Step 2: Compare Character Sets

Ensure both strings use the same characters:

if set(word1) != set(word2): return False

Step 3: Compare Frequency Counts

Count frequencies with Counter and compare sorted values:

sorted(count1.values()) == sorted(count2.values())

Why This Solution Works

This approach works because:

  • Swapping characters doesn’t change the set of characters or their frequencies.
  • Transforming characters doesn’t change the overall distribution of frequencies.
  • By validating set equality and sorted frequency equality, we cover all transformation cases.

Time and Space Complexity

  • Time Complexity:
    • Building counters: O(n + m)
    • Sorting frequencies: O(n log n) (in worst case)
  • Space Complexity: O(n) for storing counts.

Edge Cases to Consider

InputOutputExplanation
word1 = "aaab", word2 = "bbba"TrueSame characters {a, b}, same frequencies [1,3].
word1 = "abc", word2 = "abd"FalseCharacter sets differ.
word1 = "aabbcc", word2 = "xxyyzz"FalseCharacter sets don’t match.

Real-World Applications

This problem reflects string similarity checks used in real systems, such as:

  • Plagiarism detection: Comparing text structures with rearrangements.
  • Cryptography: Verifying frequency distributions of encoded messages.
  • Data cleaning: Checking if datasets contain the same distributions of attributes.

Conclusion

The Determine if Two Strings Are Close problem is a great way to strengthen your skills in sets, counters and frequency analysis. By checking character sets and matching frequency distributions, we solve the problem efficiently in O(n log n) time.

This type of problem builds intuition for handling string transformations and frequency-based checks, concepts that appear in both technical interviews and practical applications like cryptography, text analysis and anomaly detection.

1 thought on “Determine if Two Strings Are Close in Python – LeetCode75 Explained”

Leave a Comment