We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Determine if Two Strings Are Close

Number: 1777

Difficulty: Medium

Paid? No

Companies: Apple, Google, Amazon, Adobe, Meta, Postmates


Problem Description

Given two strings word1 and word2, determine if they are "close". Two strings are considered close if you can transform one into the other using the following operations as many times as needed:

  1. Swap any two existing characters.
  2. Transform every occurrence of one existing character into another existing character, and do the same with the other character. Return true if word1 and word2 are close, and false otherwise.

Key Insights

  • The set of unique characters in both strings must be identical; if they differ, no series of transformations can make the strings equal.
  • The frequency distribution (multiset of frequencies) of characters can be rearranged via transformations; hence, sorting the list of frequencies should yield the same result if the strings are close.
  • Swapping can rearrange characters arbitrarily, so positions don't matter—only the counts do.
  • Use hash maps (or frequency counters) to count occurrences and then compare.

Space and Time Complexity

Time Complexity: O(n + m + k log k) where n and m are the lengths of the two strings and k is the number of unique characters (at most 26).
Space Complexity: O(k), for storing the frequencies.


Solution

The solution involves two main checks:

  1. Ensure both strings have exactly the same unique set of characters.
  2. Compare the sorted frequency counts of each string.
    If both conditions are met, the strings can be transformed into each other using the allowed operations. Hash maps (or dictionaries) are used to count character frequencies, and sorting is applied on their values to compare frequency distributions.

Code Solutions

# Python solution with line-by-line comments
from collections import Counter

def closeStrings(word1, word2):
    # If the lengths differ, they cannot be close.
    if len(word1) != len(word2):
        return False
    
    # Count frequency of each character in word1 and word2.
    counter1 = Counter(word1)
    counter2 = Counter(word2)
    
    # Check if both strings have the same set of characters.
    if set(counter1.keys()) != set(counter2.keys()):
        return False
    
    # Compare the sorted frequency distributions.
    if sorted(counter1.values()) != sorted(counter2.values()):
        return False
    
    return True

# Example usage:
print(closeStrings("cabbba", "abbccc"))  # Expected output: True
← Back to All Questions