code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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