0
0
C Sharp (C#)programming~5 mins

Indexer with custom types in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Indexer with custom types
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of stored points grows, the dictionary lookup time stays mostly steady because it uses hashing.

Input Size (n)Approx. Operations
10About 1 operation
100About 1 operation
1000About 1 operation

Pattern observation: Lookup time does not grow much as more items are added, thanks to hashing.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how custom types work as keys helps you explain how data structures manage complex data efficiently.

Self-Check

"What if the Point class did not override GetHashCode and Equals? How would the time complexity change?"