Switch expressions with patterns in C Sharp (C#) - Time & Space 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?
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 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.
Each time we call the switch expression, it checks patterns in order until one fits.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | Checks up to 4 patterns |
| 10 | Checks up to 4 patterns per call, 10 calls total |
| 100 | Checks 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.
Time Complexity: O(n)
This means the total time grows directly with how many times we run the switch expression.
[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.
Understanding how pattern matching scales helps you explain code efficiency clearly and confidently.
"What if we added more patterns to the switch expression? How would the time complexity change?"