Skip to main content

18. Group Anagrams

mediumAsked at MercadoLibre

Cluster strings that are anagrams of each other.

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

Problem

Given an array of strings strs, group the anagrams together. Return the groups 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
[["eat","tea","ate"],["tan","nat"],["bat"]]

Example 2

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

Approaches

1. Pairwise compare

For each new string, compare against every existing group's first element.

Time
O(n^2 * k)
Space
O(n*k)
const groups = [];
outer: for (const s of strs) {
  for (const g of groups) {
    if (g[0].length === s.length && [...g[0]].sort().join('') === [...s].sort().join('')) {
      g.push(s); continue outer;
    }
  }
  groups.push([s]);
}
return groups;

Tradeoff:

2. Sorted-string key

Use the sorted characters as a hash-map key; bucket each input under that key.

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

Tradeoff:

MercadoLibre-specific tips

MercadoLibre search-relevance teams ask this because the same canonical-key pattern dedupes seller titles like 'iPhone 15 Pro' vs 'Pro iPhone 15' across regional catalogs.

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

Practice these live with InterviewChamp.AI →