Two strings str1 and str2 are similar if we can swap two letters (in different positions) of str1, so that it equals str2. Also, two strings str1 and str2 are similar if they are equal.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".
Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar.
Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
Given a list arr of strings where every string in arr is an anagram of every other string in arr. We are required to write a function that finds out how many groups are there.
Example
Following is the code −
const arr = ["tars","rats","arts","star"]; const isSimilar = (str1, str2) => { const obj = {} let counter = 0 for(let i=0; i< str1.length; i++){ if(str1[i] !== str2[i]) { counter++ } obj[str1[i]] = str2[i] } return counter === 2? true : false } const similarStringGroup = (arr = []) => { const group = [[arr[0]]] for(let i=1; i<arr.length; i++){ let match = false for(let j=0; j<group.length; j++){ for(let k=0; k< group[j].length; k++){ const booleanMatch = isSimilar(group[j][k], arr[i]) if(booleanMatch) { group[j].push(arr[i]); match = true break; } } if(match === true) { break } } if(match === false){ group.push([arr[i]]) } } return group.length } console.log(similarStringGroup(arr));
Output
Following is the console output −
2