Skip to main content

17. Group Anagrams

mediumAsked at Swiggy

Group an array of strings by their anagram equivalence class.

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

Problem

Given an array of strings strs, group the strings that are anagrams of one another. Return the groups in any order; the strings inside a group also 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 anagram check

Compare every pair via sorting.

Time
O(n^2 * k log k)
Space
O(n)
function isAna(a,b){return a.split('').sort().join('')===b.split('').sort().join('');}
// quadratic grouping via union-find or visited flags

Tradeoff:

2. Sorted-string hash key

Sort each string and use the sorted form as a map key. All anagrams collapse to the same key, so a single pass partitions the input.

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:

Swiggy-specific tips

Swiggy interviewers want you to articulate why the sorted form is a canonical key; that habit translates directly into deduping restaurant menu items by canonical name.

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

Practice these live with InterviewChamp.AI →