Positional patterns in C Sharp (C#) - Time & Space Complexity
We want to understand how long it takes for a program using positional patterns to run as the input grows.
Specifically, how does the time change when matching patterns in data structures?
Analyze the time complexity of the following code snippet.
record Point(int X, int Y);
string DescribePoint(Point p) => p switch
{
(0, 0) => "Origin",
(var x, 0) => $"X={x} on X-axis",
(0, var y) => $"Y={y} on Y-axis",
(var x, var y) => $"Point at ({x},{y})"
};
This code uses positional patterns to check where a point lies and returns a description.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Matching the input point against each pattern in the switch.
- How many times: Each call checks up to 4 patterns in order until one matches.
Each point checked runs through the same fixed number of pattern checks.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 40 pattern checks (10 points x 4 patterns) |
| 100 | About 400 pattern checks |
| 1000 | About 4000 pattern checks |
Pattern observation: The number of operations grows directly with the number of points checked.
Time Complexity: O(n)
This means the time to run grows in a straight line as you check more points.
[X] Wrong: "Positional patterns make the code run slower exponentially because of multiple checks."
[OK] Correct: Each pattern check is constant time and fixed in number, so total time grows linearly with input size, not exponentially.
Understanding how pattern matching scales helps you explain your code's efficiency clearly and confidently.
What if we added more patterns to the switch? How would the time complexity change?