Given a list of strings, group anagrams together. An anagram is a word formed by rearranging the letters of another word.

Your method should:

  • Group words that are anagrams of each other (case-insensitive comparison)
  • Return a List of List of Strings where each inner list contains anagram groups
  • Preserve the original case of the input words in the output
  • Return an empty list for empty input
  • Return null for null input

The order of groups in the output does not matter, and the order of words within each group does not matter.

Examples

Example 1: Basic Anagram Grouping

List<String> words = new List<String>{'eat', 'tea', 'tan', 'ate', 'nat', 'bat'};
List<List<String>> result = groupAnagrams(words);
// Returns: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Example 2: Single Empty String

List<String> words = new List<String>{''};
List<List<String>> result = groupAnagrams(words);
// Returns: [['']]

Example 3: Empty List

List<String> words = new List<String>();
List<List<String>> result = groupAnagrams(words);
// Returns: []

Example 4: Null Input

List<String> words = null;
List<List<String>> result = groupAnagrams(words);
// Returns: null

Example 5: Case Preservation

List<String> words = new List<String>{'Eat', 'Tea', 'EAT'};
List<List<String>> result = groupAnagrams(words);
// Returns: [['Eat', 'Tea', 'EAT']]
// All are anagrams (case-insensitive), original case preserved
Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay Feb 2026

Contest runs February 1 - 28. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.