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

Positional patterns in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Positional patterns
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

Each point checked runs through the same fixed number of pattern checks.

Input Size (n)Approx. Operations
10About 40 pattern checks (10 points x 4 patterns)
100About 400 pattern checks
1000About 4000 pattern checks

Pattern observation: The number of operations grows directly with the number of points checked.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as you check more points.

Common Mistake

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

Interview Connect

Understanding how pattern matching scales helps you explain your code's efficiency clearly and confidently.

Self-Check

What if we added more patterns to the switch? How would the time complexity change?