hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Determine if Two Strings Are Close


  • Approach:

  1. Calculated the frequency of each character for both strings.

  2. Checked if any of the characters of the word2 is missing for word1. If it is, then returned False.

  3. Then sorted the character appearance counts for both the strings.

  4. Then checks if the count is equal for each i'th index. If not, then returned False.

  5. Else returned True.


  • Time and Space Complexity:

    • Time complexity:O(N) + O(Clog2C), where C = 26

    • Space complexity: O(C), where C = 26


Code [C++]

class Solution {

public:

bool closeStrings(string word1, string word2) {

int n1 = word1.size();

int n2 = word2.size();

if(n1 != n2) return false;

vector<int>freq_w1(26, 0), freq_w2(26, 0);

for(int i=0; i<n1; i++) freq_w1[word1[i] - 'a']++;

for(int i=0; i<n2; i++){

if(freq_w1[word2[i] - 'a'] == 0) return false;

freq_w2[word2[i] - 'a']++;

}

sort(freq_w1.begin(), freq_w1.end());

sort(freq_w2.begin(), freq_w2.end());

for(int i=0; i<26; i++){

if(freq_w1[i] != freq_w2[i]) return false;

}

return true;

}

};