Dictionary methods and access patterns in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use dictionaries in C#, it is important to know how fast we can find, add, or remove items.
We want to understand how the time to do these actions changes as the dictionary grows.
Analyze the time complexity of the following code snippet.
var dict = new Dictionary<string, int>();
// Add items
for (int i = 0; i < n; i++)
{
dict[$"key{i}"] = i;
}
// Access items
for (int i = 0; i < n; i++)
{
int value = dict[$"key{i}"];
}
This code adds n items to a dictionary and then accesses each item by its key.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding and accessing items in the dictionary inside loops.
- How many times: Each operation happens n times, once per loop iteration.
Each add or access takes about the same time, no matter how big the dictionary is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 adds + 10 accesses = 20 operations |
| 100 | About 100 adds + 100 accesses = 200 operations |
| 1000 | About 1000 adds + 1000 accesses = 2000 operations |
Pattern observation: The total work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the total time grows in a straight line with the number of items added and accessed.
[X] Wrong: "Accessing dictionary items takes longer as the dictionary gets bigger because it searches through all items."
[OK] Correct: Dictionaries use a special method to find items quickly, so access time stays about the same no matter the size.
Knowing how dictionary operations scale helps you write fast and efficient code, a skill valued in many programming tasks.
"What if we used a list instead of a dictionary for storing and accessing items by key? How would the time complexity change?"
Practice
ContainsKey method do in a C# Dictionary?Solution
Step 1: Understand the purpose of ContainsKey
TheContainsKeymethod checks if a given key is present in the dictionary.Step 2: Compare with other dictionary methods
Addadds items,Removedeletes items, andCountreturns the number of items, so these are different fromContainsKey.Final Answer:
Checks if a specific key exists in the dictionary -> Option AQuick Check:
ContainsKey checks key presence [OK]
- Confusing ContainsKey with Add method
- Thinking ContainsKey returns a value instead of a boolean
- Mixing ContainsKey with Count property
Dictionary<string, int> named ages?Solution
Step 1: Recall the syntax for adding items to Dictionary
The correct method to add a key-value pair isAdd(key, value).Step 2: Check each option's syntax
ages.Add("Alice", 30); usesAdd("Alice", 30)which is correct. ages.Add["Alice"] = 30; uses square brackets with Add which is invalid. ages["Alice"].Add(30); tries to call Add on the value, which is wrong. ages.Insert("Alice", 30); uses Insert which does not exist for Dictionary.Final Answer:
ages.Add("Alice", 30); -> Option AQuick Check:
Add(key, value) syntax [OK]
- Using square brackets with Add method
- Trying to call Add on a value instead of dictionary
- Using Insert method which does not exist
var dict = new Dictionary<string, int>();
dict.Add("x", 10);
dict["y"] = 20;
Console.WriteLine(dict["x"] + dict["y"]);Solution
Step 1: Understand dictionary additions
First,dict.Add("x", 10)adds key "x" with value 10. Thendict["y"] = 20adds key "y" with value 20.Step 2: Calculate the sum printed
dict["x"]is 10 anddict["y"]is 20, so their sum is 30.Final Answer:
30 -> Option BQuick Check:
10 + 20 = 30 [OK]
- Expecting output as separate values instead of sum
- Confusing keys and values in output
- Thinking dict["y"] is invalid without Add
var dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("a", 2);
Console.WriteLine(dict["a"]);Solution
Step 1: Understand Add method behavior with duplicate keys
TheAddmethod throws an exception if the key already exists.Step 2: Analyze the code flow
The firstAdd("a", 1)works fine. The secondAdd("a", 2)tries to add the same key again, causing an exception.Final Answer:
Duplicate key exception on second Add call -> Option CQuick Check:
Adding duplicate key throws exception [OK]
- Assuming Add overwrites existing keys
- Expecting no error and value updated
- Confusing Add with indexer assignment
scores with student names as keys and their scores as values, which code snippet safely retrieves the score for "John" without causing an error if the key is missing?Solution
Step 1: Understand safe retrieval methods
UsingTryGetValuesafely tries to get the value and returns false if key is missing without error.Step 2: Analyze each option
int score = scores["John"]; throws an exception if "John" is missing. int score = scores.GetValueOrDefault("John"); is invalid in C# Dictionary (GetValueOrDefault is not standard). scores.TryGetValue("John", out int score); uses TryGetValue correctly. int score = scores.ContainsKey("John"); returns a boolean, not the score.Final Answer:
scores.TryGetValue("John", out int score); -> Option DQuick Check:
TryGetValue safely gets value [OK]
- Using indexer without checking key existence
- Confusing ContainsKey with value retrieval
- Expecting GetValueOrDefault method on Dictionary
