You are given an array of strings. Your task is to group the strings that are anagrams of each other. Two strings are anagrams if they contain the same characters in the same frequency, but the order of characters does not matter.
3Times asked
Apr 2026Last seen
Apr 2026First seen
💡 Model Answer
A common approach is to use a hash map where the key is a canonical representation of each string and the value is a list of strings that match that key. Two canonical forms are popular:
- Sorted string – sort the characters of each string (O(k log k) per string, where k is the string length). Use the sorted string as the key.
- Character count – build a 26‑element array (or a 256‑element array for full ASCII) counting each character. Convert the array to a string or tuple to use as the key. This is O(k) per string.
Algorithm:
- Initialize an empty map.
- For each string s in the array:
- Compute its key (sorted or count).
- Append s to map[key].
- Return the list of all map values.
Complexity: If using sorting, time is O(n k log k) and space is O(n k). Using counting reduces time to O(n * k) while keeping space similar. The algorithm is straightforward, works for any alphabet, and handles duplicates naturally.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500