Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Similar string groups in JavaScript
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 {
const group = [[arr[0]]]
for(let i=1; i
Output
Following is the console output −
2
