Skip to main content

19. Group Anagrams

mediumAsked at Ramp

Bucket strings that are anagrams of each other together.

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

Problem

Given an array of strings strs, group the anagrams together. You can return the answer in any order. An anagram is a word formed by rearranging the letters of another word.

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. Brute force pairwise compare

Compare every pair of sorted strings to bucket them.

Time
O(n^2 * k log k)
Space
O(nk)
function groupAnagrams(strs) {
  const used = new Array(strs.length).fill(false);
  const out = [];
  for (let i = 0; i < strs.length; i++) {
    if (used[i]) continue;
    const group = [strs[i]];
    used[i] = true;
    const key = strs[i].split('').sort().join('');
    for (let j = i + 1; j < strs.length; j++) {
      if (!used[j] && strs[j].split('').sort().join('') === key) { group.push(strs[j]); used[j] = true; }
    }
    out.push(group);
  }
  return out;
}

Tradeoff:

2. Hash map keyed by sorted string

Sort each string once; use the sorted form as a map key to a list of originals.

Time
O(n * k log k)
Space
O(nk)
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:

Ramp-specific tips

Ramp's vendor-matching engine fingerprints merchant names into canonical keys exactly like this — a hash-key bucketing answer here signals you can build the same dedup primitive at production scale.

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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →