1657. Determine if Two Strings Are Close

Description of Problem

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

Constraints:

  • 1 <= word1.length, word2.length <= 10^5
  • word1 and word2 contain only lowercase English letters.

Solution 1 - using HashSet+HashMap (Not Optimised)

Tags: HashSet/HashMap

Explanation

Intutive Explanation

Two strings are close if and only if they have the same set of characters and the same list of number of occurrences unorderly.

Explanation by String Compression

By operation 1, orders of two strings do not matter. Thus, we can compress string into (cN)* format where c is character and N is number of occurrences of c; cN is ordered by c in alphabetical order. For example, cabbba becomes a2b3c1 and abbccc becomes a1b2c3. Thus, Operation 2 is equivalent to swapping numbers in compressed string.

  • If two strings have different set of characters, they are not close.
  • If two strings have different list of number of occurrences of characters unorderly, they are not close
  • Otherwise, we can keep swapping occurrences list until its order is the same as the another list. (e.g. 231 -> 132 -> 123). Therefore, they are close.

Code

impl Solution {
    pub fn close_strings(word1: String, word2: String) -> bool {
        use std::collections::HashMap;
        use std::collections::HashSet;

        if (word1.len() != word2.len()){
            return false;
        }

        let mut m1 = HashMap::new();
        let mut m2 = HashMap::new();

        for ch in word1.chars() {
            m1.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
        }

        for ch in word2.chars() {
            m2.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
        }

        let mut k1 : HashSet<_> = m1.keys().map(|&v| v ).collect(); 
        let mut k2 : HashSet<_> = m2.keys().map(|&v| v ).collect();
        
        if (k1 != k2){
            return false;
        }

        let mut m1 : Vec<_> = m1.values().map(|&v| v ).collect(); 
        let mut m2 : Vec<_> = m2.values().map(|&v| v ).collect(); 

        m1.sort(); m2.sort();

        return m1 == m2;
    }
}

Complexity

  • m is length of word1
  • n is legnth of word2
  • The following calculation assume there is non-ASCII characters

Time Complexity

  • \( T(m,n) = O( 3m + 3n + m \lg m + n \lg n + \min(m,n) ) = O( \min(m,n) \lg \min(m,n) ) \)
    1. O(m + n) : Create 2 HashMaps
    2. O(m + n) : Create 2 HashSets
    3. O(m + n) : Create 2 Vectors for occurrence.
    4. O(m \lg m + n \lg n) : Sort 2 Vectors
    5. O(min(m,n)) : Compare 2 Vectors

Auxiliary Space

  • \( S(m,n) = O( m + n ) \)
    • For HashSets, HashMaps and Vectors

Solution 2 - using Array

Tags: HashSet/HashMap

Code

impl Solution {
    pub fn close_strings(word1: String, word2: String) -> bool {
        if word1.len() != word2.len() { return false; }

        let (mut c1, mut c2) = (vec![ 0 ; 26 ], vec![ 0 ; 26 ]);

        for ch in word1.chars(){ c1[ ch as usize - 97 ] +=1; }

        for ch in word2.chars(){ c2[ ch as usize - 97 ] +=1; }

        for i in 0..26{
            if (c1[i] > 0) ^ (c2[i] > 0) {
                return false;
            }
        }

        c1.sort();c2.sort();
        return c1==c2;
    }
}

Complexity

  • m is length of word1
  • n is legnth of word2

Time Complexity

  • \( T(m,n) = O(m+n) \)
    • Only counting depends on the input size

Auxiliary Space

  • \( S(m,n) = O(1) \)