Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a dictionary that groups anagrams by their sorted key.
DSA C#
var map = new Dictionary<string, List<string>>(); foreach (var word in words) { var key = new string(word.ToCharArray()[1]); if (!map.ContainsKey(key)) { map[key] = new List<string>(); } map[key].Add(word); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using .Sort() directly on the array without converting to string.
Not sorting the characters before creating the key.
✗ Incorrect
We convert the word to a char array, sort it using OrderBy, then create a new string as the key.
2fill in blank
mediumComplete the code to return the grouped anagrams as a list of lists.
DSA C#
return map.Values.[1](list => list.ToList()).ToList();
Attempts:
3 left
💡 Hint
Common Mistakes
Using Where instead of Select.
Trying to use GroupBy again on the values.
✗ Incorrect
We use Select to convert each value (ICollection) to a List and then collect them into a List
- >.
3fill in blank
hardFix the error in the code that tries to add a word to the dictionary list.
DSA C#
if (!map.ContainsKey(key)) { map[key] = new List<string>(); } map.[1](key).Add(word);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Add method on dictionary which expects a key-value pair.
Using Remove which deletes entries.
✗ Incorrect
GetValueOrDefault returns the list for the key, allowing Add to be called safely.
4fill in blank
hardFill both blanks to correctly sort characters and add words to the dictionary.
DSA C#
foreach (var word in words) { var key = new string(word.ToCharArray()[1]); if (!map.[2](key)) { map[key] = new List<string>(); } map[key].Add(word); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using ContainsValue instead of ContainsKey.
Using Reverse instead of sorting characters.
✗ Incorrect
Sort characters with OrderBy and check if key exists with ContainsKey before adding.
5fill in blank
hardFill all three blanks to create the grouped anagrams dictionary and return the result.
DSA C#
var map = new Dictionary<string, List<string>>(); foreach (var word in words) { var key = new string(word.ToCharArray()[1]); if (!map.[2](key)) { map[key] = new List<string>(); } map[key].Add(word); } return map.Values.[3](list => list.ToList()).ToList();
Attempts:
3 left
💡 Hint
Common Mistakes
Using Where instead of Select for projection.
Using ContainsValue instead of ContainsKey.
Not sorting characters before creating the key.
✗ Incorrect
Sort characters for key, check key existence with ContainsKey, and use Select to convert groups to lists.
