Indexer with custom types in C Sharp (C#) - Time & Space Complexity
When using an indexer with custom types, it's important to know how the time to access elements changes as the collection grows.
We want to find out how fast or slow accessing items is when using a custom type as the index.
Analyze the time complexity of the following code snippet.
public class Point {
public int X { get; set; }
public int Y { get; set; }
public override bool Equals(object obj) {
if (obj is Point other) {
return X == other.X && Y == other.Y;
}
return false;
}
public override int GetHashCode() {
return HashCode.Combine(X, Y);
}
}
public class Grid {
private Dictionary<Point, string> data = new();
public string this[Point p] {
get => data[p];
set => data[p] = value;
}
}
This code defines a grid that stores strings at points using a dictionary with a custom Point type as the key.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Dictionary lookup by custom key (Point).
- How many times: Each access calls the dictionary's internal search once.
As the number of stored points grows, the dictionary lookup time stays mostly steady because it uses hashing.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation |
| 100 | About 1 operation |
| 1000 | About 1 operation |
Pattern observation: Lookup time does not grow much as more items are added, thanks to hashing.
Time Complexity: O(1)
This means accessing an element by a custom type index takes about the same time no matter how many items are stored.
[X] Wrong: "Using a custom type as an index makes access slower because it has to check every item."
[OK] Correct: The dictionary uses hashing and equality checks, so it does not scan all items but finds the right one quickly.
Understanding how custom types work as keys helps you explain how data structures manage complex data efficiently.
"What if the Point class did not override GetHashCode and Equals? How would the time complexity change?"