Skip to main content

20. Group Anagrams

mediumAsked at Grab

Bucket strings that are anagrams of one another — Grab uses this to test hash-key selection.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array of strings, group the anagrams together. You can return the answer in any order.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters

Examples

Example 1

Input
strs = ["eat","tea","tan","ate","nat","bat"]
Output
[["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2

Input
strs = [""]
Output
[[""]]

Approaches

1. All-pairs comparison

For each new string, compare against every group representative.

Time
O(n^2 * k)
Space
O(n)
const groups = [];
for (const s of strs) {
  let placed = false;
  for (const g of groups) {
    if (isAnagram(g[0], s)) { g.push(s); placed = true; break; }
  }
  if (!placed) groups.push([s]);
}

Tradeoff:

2. Sorted-key hash

Sort each string's characters to form a canonical key; bucket into a Map.

Time
O(n * k log k)
Space
O(n * k)
function groupAnagrams(strs) {
  const map = new Map();
  for (const s of strs) {
    const key = s.split('').sort().join('');
    if (!map.has(key)) map.set(key, []);
    map.get(key).push(s);
  }
  return [...map.values()];
}

Tradeoff:

Grab-specific tips

Grab interviewers reward fast hash-key choices — frame as deduping driver+vehicle keys across regional partitions in their SEA dispatch system.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Group Anagrams and other Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →