DEV Community

seonglinchua
seonglinchua

Posted on

Mastering Dictionary<TKey, TValue> in C# for Coding Interviews

๐Ÿ”‘ Dictionary in C# โ€” The Ultimate Tool for Fast Lookup

A Dictionary<TKey, TValue> is a powerful data structure that maps unique keys to values, allowing fast O(1) lookups and efficient data grouping.


โœ… When to Use Dictionary

Use Case Why Use Dictionary
Map key to value Quick access with known key
Frequency count Count how many times items appear
Grouping elements Categorize data using keys
Implement cache or memoization Fast storage and retrieval

โœ๏ธ Declaring and Initializing

// Declare and initialize
Dictionary<string, int> ageMap = new Dictionary<string, int>();

// Adding entries
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Common Operations

// Add or update
ageMap["Charlie"] = 28;

// Check key existence
if (ageMap.ContainsKey("Alice"))
    Console.WriteLine(ageMap["Alice"]);

// Remove entry
ageMap.Remove("Bob");

// Loop through dictionary
foreach (var kvp in ageMap)
{
    Console.WriteLine($"{kvp.Key} => {kvp.Value}");
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Interview Example 1: Two Sum

public int[] TwoSum(int[] nums, int target)
{
    var map = new Dictionary<int, int>();
    for (int i = 0; i < nums.Length; i++)
    {
        int complement = target - nums[i];
        if (map.ContainsKey(complement))
            return new int[] { map[complement], i };
        map[nums[i]] = i;
    }
    return new int[] { -1, -1 };
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Interview Example 2: Group Anagrams

public IList<IList<string>> GroupAnagrams(string[] strs)
{
    var map = new Dictionary<string, List<string>>();

    foreach (var word in strs)
    {
        char[] chars = word.ToCharArray();
        Array.Sort(chars);
        string key = new string(chars);

        if (!map.ContainsKey(key))
            map[key] = new List<string>();

        map[key].Add(word);
    }

    return new List<IList<string>>(map.Values);
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Summary

Feature Syntax Example
Declare new Dictionary<TKey, TValue>()
Add/Update dict[key] = value;
Exists Check dict.ContainsKey(key)
Remove dict.Remove(key)
Iterate foreach (var kvp in dict)

Next up: Stack โ€” ideal for solving nested and reverse order problems like Valid Parentheses and backtracking tasks.

Top comments (1)

Collapse
 
ghost_engineer_2883a1ca0a profile image
Ghost Engineer

try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com