1657.Determine if Two Strings Are Close
- Manbodh ratre
- Dec 18, 2022
- 1 min read
Updated: May 12, 2024
Intuition
in this question we have to check 3 conditions
all the character of word1 should be present on word2 and vice-versa
the character frequency count should be equal
Approach
in this question we have to check 3 conditions
all the character of word1 should be present on word2 and vice-versa
the character frequency count should be equal example: w1 = abbccdde, w2 = eeaacbbd
Here for w1: 1 times of character = 2(a,e) 2 times of character = 3(b,c,d)
and in w2: 1 times of character = 2(c,d) 2 times of character = 3(e,a,b)
So In w1 and w2 both the freq of characters are equal, hence it is valid answer.
Complexity
Time complexity:
First check : To check every character is present on both words will take O(n) time Second Check : checkAnotherCondition this method is also taking O(n) so the overall time complexity is O(n);
Space complexity:
O(1)
Solution
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length()!=word2.length())
return false;
return checkAns(word1,word2)&&checkAns(word2,word1)&&checkAnotherCondition(word1,word2);
}
public boolean checkAns(String word1,String word2){
HashMap<Character,Boolean> map = new HashMap<>();
for(int i=0;i<word1.length();i++){
map.put(word1.charAt(i),true);
}
for(int i=0;i<word2.length();i++){
if(!map.containsKey(word2.charAt(i))){
return false;
}
}
return true;
}
public boolean checkAnotherCondition(String word1,String word2){
HashMap<Integer,Integer> map1 = getValue(word1);
HashMap<Integer,Integer> map2 = getValue(word2);
for(Map.Entry<Integer,Integer> map : map1.entrySet()){
if(map2.get(map.getKey())!=map.getValue())
return false;
}
return true;
}
public HashMap<Integer,Integer> getValue(String word){
HashMap<Character,Integer> freq = new HashMap<>();
for(int i=0;i<word.length();i++){
char c = word.charAt(i);
freq.put(c,freq.getOrDefault(c,0)+1);
}
HashMap<Integer,Integer> values = new HashMap<>();
for(Map.Entry<Character,Integer> ans:freq.entrySet()){
int val = ans.getValue();
values.put(val,values.getOrDefault(val,0)+1);
}
return values;
}
}






Comments