Bird
Raised Fist0
Interview Prephash-maps-setsmediumAmazonFacebookGoogleBloomberg

Group Anagrams

Choose your preparation mode4 modes available
</>
IDE
def groupAnagrams(strs: list[str]) -> list[list[str]]:public List<List<String>> groupAnagrams(String[] strs)vector<vector<string>> groupAnagrams(vector<string>& strs)function groupAnagrams(strs)
def groupAnagrams(strs):
    # Write your solution here
    pass
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
#include <string>
using namespace std;

vector<vector<string>> groupAnagrams(vector<string>& strs) {
    // Write your solution here
    return {};
}
function groupAnagrams(strs) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: [['eat', 'tea'], ['tan', 'nat'], ['ate'], ['bat']]Grouping strings incorrectly by comparing only first characters or partial keys, causing 'ate' to be separated.✅ Use full sorted string as key for grouping all anagrams together.
Wrong: [['aabb', 'baba', 'abab'], ['bbaa'], ['aaab', 'abaa']]Failing to group all anagrams with repeated characters together due to partial key or set usage.✅ Use sorted strings as keys to capture exact character counts and group all anagrams correctly.
Wrong: [['abc', 'cab', 'bac', 'abcabc', 'bcaabc', 'aabbcc']]Merging groups with different character counts by ignoring multiplicity (0/1 vs unbounded confusion).✅ Use sorted strings or frequency count tuples as keys to distinguish groups by exact character counts.
Wrong: Timeout or no output on large inputUsing brute force pairwise comparison (O(n^2)) instead of hashing.✅ Use hash map with sorted string keys to achieve O(n*k log k) time complexity.
Wrong: [['a'], ['b'], ['c'], ['a'], ['b'], ['c']]Failing to group identical strings together; possibly using reference equality or not grouping at all.✅ Group strings by their sorted keys and append all matching strings to the same group.
✓
Test Cases
t1_01basic
Input["eat","tea","tan","ate","nat","bat"]
Expected[["eat","tea","ate"],["tan","nat"],["bat"]]

The words 'eat', 'tea', and 'ate' are anagrams of each other, as are 'tan' and 'nat'. 'bat' has no anagram in the list.

t1_02basic
Input["abc","bca","cab","xyz","zyx","zxy"]
Expected[["abc","bca","cab"],["xyz","zyx","zxy"]]

Two groups of anagrams: 'abc', 'bca', 'cab' and 'xyz', 'zyx', 'zxy'.

t2_01edge
Input[]
Expected[]

Empty input array returns empty list.

t2_02edge
Input[""]
Expected[[""]]

Single empty string forms one group containing that string.

t2_03edge
Input["a","b","c"]
Expected[["a"],["b"],["c"]]

No anagrams present; each string forms its own group.

t2_04edge
Input["","",""]
Expected[["","",""]]

All strings are empty; groups all empty strings together.

t3_01corner
Input["abc","bca","abcd","bcda","abdc","xyz"]
Expected[["abc","bca"],["abcd","bcda","abdc"],["xyz"]]

Groups with different lengths and overlapping characters; tests correct key grouping by sorted strings.

t3_02corner
Input["aabb","baba","abab","bbaa","aaab","abaa"]
Expected[["aabb","baba","abab","bbaa"],["aaab","abaa"]]

Tests grouping with repeated characters and similar but different counts.

t3_03corner
Input["abc","cab","bac","abcabc","bcaabc","aabbcc"]
Expected[["abc","cab","bac"],["abcabc","bcaabc","aabbcc"]]

Tests confusion between 0/1 and unbounded counts; 'abc' and 'abcabc' groups differ by character counts.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 with strings length up to 100; solution must run in O(n*k log k) or better within 2 seconds.

Practice

(1/5)
1. You are given an array of integers and need to determine if any value appears at least twice. Which approach guarantees the most efficient detection of duplicates in terms of time complexity?
easy
A. Sort the array and then scan once to check if any adjacent elements are equal.
B. Use a hash set to track seen elements and check membership while iterating once.
C. Use nested loops to compare every pair of elements for equality.
D. Use dynamic programming to build a table of duplicate occurrences.

Solution

  1. Step 1: Understand the problem requirements

    The problem requires detecting duplicates efficiently in an array.
  2. Step 2: Compare approaches based on time complexity

    Sorting then scanning is O(n log n), nested loops is O(n²), and dynamic programming is unnecessary here. Using a hash set allows O(n) time with O(n) space by checking membership during one pass.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Hash set membership check is O(1) average, enabling linear time detection [OK]
Hint: Hash set membership check enables linear time detection [OK]
Common Mistakes:
  • Confusing sorting approach as optimal
  • Thinking nested loops are efficient enough
  • Misapplying DP to a membership problem
2. You need to design a data structure that supports inserting elements, deleting elements, and retrieving a random element, all in average constant time. Which approach best guarantees this performance?
easy
A. Using a balanced binary search tree to maintain elements and their indices
B. Combining a hash map for element indices with an array to store elements, using a swap-delete trick on removal
C. Using a linked list for elements and a hash set for membership checks
D. Maintaining a sorted array and performing binary search for insertions and deletions

Solution

  1. Step 1: Understand operation requirements

    Insert, delete, and getRandom must all be O(1) average time.
  2. Step 2: Evaluate data structures

    Balanced BST or sorted array have O(log n) or worse for insert/delete. Linked list lacks O(1) random access. Hash map + array with swap-delete achieves O(1) for all operations.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Hash map + array with swap-delete is the classic O(1) solution [OK]
Hint: Hash map + array with swap-delete enables O(1) ops [OK]
Common Mistakes:
  • Thinking balanced BST gives O(1) insert/delete
  • Using linked list for O(1) random access
  • Assuming sorted array can do O(1) insert/delete
3. Consider the following Python function to check if two strings are isomorphic:
def isIsomorphic(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False
    s_to_t = {}
    t_to_s = {}
    for c1, c2 in zip(s, t):
        if c1 in s_to_t:
            if s_to_t[c1] != c2:
                return False
        else:
            s_to_t[c1] = c2
        if c2 in t_to_s:
            if t_to_s[c2] != c1:
                return False
        else:
            t_to_s[c2] = c1
    return True

print(isIsomorphic("egg", "add"))
What is the output of this code?
easy
A. True
B. None
C. Raises an exception
D. False

Solution

  1. Step 1: Trace first iteration with c1='e', c2='a'

    Both maps are empty, so s_to_t['e'] = 'a' and t_to_s['a'] = 'e'.
  2. Step 2: Trace second and third iterations

    Second iteration: c1='g', c2='d', maps updated similarly. Third iteration: c1='g' already maps to 'd', and c2='d' maps back to 'g', so no conflict.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Mapping is consistent for all characters, so returns True [OK]
Hint: Check mapping consistency at each iteration [OK]
Common Mistakes:
  • Confusing output with 'foo' and 'bar'
  • Assuming length mismatch causes exception
4. Consider the following buggy get method for the time-based key-value store. Which line contains the subtle bug that causes incorrect results when querying timestamps less than the smallest stored timestamp?
medium
A. Line 6: Returning empty string if i == 0
B. Line 2: Checking if key not in store
C. Line 5: Using bisect_left instead of bisect_right
D. Line 7: Returning values[i-1]

Solution

  1. Step 1: Understand difference between bisect_left and bisect_right

    bisect_left returns insertion index to the left, which can cause off-by-one errors when timestamp equals stored timestamps.
  2. Step 2: Identify impact on retrieval

    Using bisect_left causes incorrect index i for timestamps equal to stored ones, leading to wrong value or empty string returned.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    bisect_right is required to get correct insertion point for retrieval [OK]
Hint: bisect_right needed to get correct insertion index [OK]
Common Mistakes:
  • Using bisect_left instead of bisect_right
  • Incorrect boundary check for i==0
  • Returning wrong index value
5. Suppose the time-based key-value store is extended to allow multiple values to be set at the same timestamp for a key, and get should return the most recently set value at or before the timestamp. Which modification to the data structure and retrieval algorithm is correct?
hard
A. Store multiple values per timestamp in a list and modify binary search to find the last value in that list.
B. Store timestamps with duplicates in a list and use bisect_right to find insertion index, then return the last inserted value at that timestamp.
C. Store all (timestamp, value) pairs in insertion order and perform linear search backward on get.
D. Use a hash map from (key, timestamp) to a stack of values and pop on get.

Solution

  1. Step 1: Understand requirement for multiple values per timestamp

    Multiple values at same timestamp require storing duplicates and retrieving the most recent one.
  2. Step 2: Analyze retrieval with duplicates

    Using bisect_right on timestamps list with duplicates returns insertion index after all duplicates; returning value at i-1 gives the last inserted value at that timestamp.
  3. Step 3: Confirm data structure modification

    Storing timestamps with duplicates in order and values aligned allows correct retrieval without linear search or complex structures.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    bisect_right with duplicates returns correct index for last inserted value [OK]
Hint: bisect_right handles duplicates by returning insertion after last duplicate [OK]
Common Mistakes:
  • Using linear search causing inefficiency
  • Using stacks requiring pop on get
  • Storing multiple values in nested lists complicates retrieval
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard