code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

049 Group Anagrams

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.
*/


function groupAnagrams(value) {
  let grouped = {}
  for (let index = 0; index < value.length; index++) {
    let word = value[index]
    let key = word.split('').sort().join('');
    if(!grouped[key]) {
      grouped[key] = [word]
    } else {
      grouped[key].push(word)
    }
  }
  return Object.values(grouped)
}

test('group Anagrams', () => {
  expect(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])).toEqual([
    ["ate","eat","tea"],
    ["nat","tan"],
    ["bat"]
  ])
});

Created 2020-02-23T17:46:04+00:00 · Edit