DEV Community

Think1s
Think1s

Posted on • Edited on

JS Interview Question #1 (Group Anagrams)

Read more articles in Think1s
What is Anagram?
According to wikipedia Anagram is a word, phrase, or name formed by rearranging the letters of another.
Ex: Elbow and below

let groupAnagramsObj = {};
  for (let i of distinctArrSet) {
    let groupArr = sortedArr.reduce((acc, curr, index) => {
      if (curr == i) {
        acc.push(index);
      }
      return acc;
    }, []);
    groupAnagramsObj[i] = groupArr;
  }

  // console.log(groupAnagramsObj)
  // { "below": [ 0, 1 ], "ceersu": [ 2, 3 ], "act": [ 4, 5, 6 ] }

  let anagramsGroup = [];
  for (let i in groupAnagramsObj) {
    anagramsGroup.push(groupAnagramsObj[i].map((item) => arr[item]));
  }
  return anagramsGroup;
};
console.log(
  groupAnagrams(["elbow", "rescue", "cat", "secure", "act", "below", "tac"])
);

// [["below","elbow"],["secure","rescue"],["cat","act","tac"]]
Enter fullscreen mode Exit fullscreen mode

Read more articles in Think1s

Top comments (0)