<AI/>
enru
Все статьи

Determine if two strings are close

LeetCode 1657: Check whether two strings can be transformed into each other by comparing their letter sets and frequency signatures.

Сложность
Средняя
Опубликовано
Темы
#string#hash table
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given two strings. Return true if they are close, and false otherwise.

Two strings are considered close if you can get one from the other using the following operations.

Operation 1: Swap any two existing characters. For example, abcde -> aecdb (the letters b and e were swapped).

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 as turn into bs, and all bs turn into as).

You can use the operations on either string as many times as necessary.

Constraints

  • The length of each word is in the range from 1 to 105
  • Both words contain only lowercase English letters

Examples

Input: word1 = "abc", word2 = "bca"

Answer: true

Explanation

You can get word2 from word1 in 2 operations.

  • Apply operation 1: "abc" -> "acb"
  • Apply operation 1: "acb" -> "bca"

Solution

The first thought is to write an algorithm that tries to turn one word into the other using the given operations. The problem is that the operations can be applied in any order and any number of times. Going down this path, our algorithm would take a very long time trying all possible combinations. We need a smarter and simpler solution.

First, let's take a close look at the examples, specifically the third one, more precisely, at the states of the first string as it turns into the second. For convenience, let's write them one under another and count the frequency of each letter.

cabbba: 1c, 2a, 3b
caabbb: 1c, 2a, 3b
baaccc: 1b, 2a, 3c
abbccc: 1a, 2b, 3c

Looking closely, we can see that the transformations change the letters, but the frequency numbers stay the same. Let's call this the frequency signature of the word. No matter how we transform the word, it always keeps the frequency signature [1, 2, 3].

Based on this, we can formulate two conditions that are sufficient for two strings to be close.

  1. The frequency signatures of both words must be the same.
  2. Every letter of the first word must be present in the second word, and vice versa.

In all other cases the strings are not close.

So to solve the problem we need 2 counters that count the frequency of each letter in both words. After counting, we get two sets of frequencies.

{
  "c": 1,
  "a": 2,
  "b": 3
}
{
  "c": 3,
  "a": 1,
  "b": 2
}

Now we need to compare these frequencies:

  1. Both sets must have the same number of keys, and the keys must match
  2. Both sets must have the same values (regardless of keys)

To compare the values efficiently, we can introduce a helper hash map where the key is a frequency (a value from our counters) and the value is a counter. While going over the first set we increment this counter, and while going over the second one we decrement it. If all counters end up equal to zero, the sets of frequencies are the same.

So after iterating over the first set, the helper counters look like this:

{
  1: 1,
  2: 1,
  3: 1
}

After iterating over the second set, we get the final state of the helper counters:

{
  1: 0,
  2: 0,
  3: 0
}

As an optimization, we can do both the increment and decrement in a single loop, since the sets of keys must be the same.

Since all helper counters ended up at zero, we can conclude that cabbba and abbccc are close.

typescript
const fillCounter = (word: string): Record<string, number> => {
  const counter: Record<string, number> = {};
 
  for (let i = 0; i < word.length; i++) {
    if (!counter[word[i]]) {
      counter[word[i]] = 0;
    }
    counter[word[i]]++;
  }
 
  return counter;
};
 
export const closeStrings = (word1: string, word2: string): boolean => {
  if (word1.length !== word2.length) {
    return false;
  }
 
  const counter1 = fillCounter(word1);
  const counter2 = fillCounter(word2);
  const tempCounter: Record<number, number> = {};
 
  for (const [k, v] of Object.entries(counter1)) {
    const v2 = counter2[k];
 
    if (!v2) {
      return false;
    }
 
    if (!tempCounter[v]) {
      tempCounter[v] = 0;
    }
    if (!tempCounter[v2]) {
      tempCounter[v2] = 0;
    }
 
    tempCounter[v]++;
    tempCounter[v2]--;
  }
 
  for (const [_, count] of Object.entries(tempCounter)) {
    if (count !== 0) {
      return false;
    }
  }
 
  return true;
};

Complexity Analysis

Time Complexity

To build the letter frequencies we iterate over each word once, i.e. we perform 2n operations, where n is the length of a word. We also iterate over the frequencies twice, but that can be treated as constant, since the number of letters in the English alphabet is fixed. So the time complexity is linear: O(n).

Space Complexity

The space complexity is constant: O(1). Although we allocate memory for the maps, their size is bounded, since there are only 26 letters in the English alphabet. So the additional memory can be treated as constant.