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

Switch expressions with patterns in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch expressions with patterns
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a switch expression with patterns changes as the input grows.

Specifically, how does the number of pattern checks affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


string DescribeNumber(int number) => number switch
{
    > 0 and <= 10 => "Small",
    > 10 and <= 100 => "Medium",
    > 100 => "Large",
    _ => "Unknown"
};
    

This code uses a switch expression with patterns to categorize a number into size groups.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch expression checks each pattern one by one until it finds a match.
  • How many times: At most, it checks all patterns once per call.
How Execution Grows With Input

Each time we call the switch expression, it checks patterns in order until one fits.

Input Size (n)Approx. Operations
1Checks up to 4 patterns
10Checks up to 4 patterns per call, 10 calls total
100Checks up to 4 patterns per call, 100 calls total

Pattern observation: The number of checks per call stays the same, but total work grows linearly with calls.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly with how many times we run the switch expression.

Common Mistake

[X] Wrong: "Switch expressions with patterns always take the same time no matter how many inputs."

[OK] Correct: Each call does a fixed number of checks, but if you run it many times, total time adds up.

Interview Connect

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

Self-Check

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