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

Pattern matching in switch in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Pattern matching in switch
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a switch statement with pattern matching changes as the input changes.

Specifically, how does the number of checks grow when we add more patterns?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


object obj = GetInput();
switch (obj)
{
    case int i:
        Console.WriteLine($"Integer: {i}");
        break;
    case string s when s.Length > 5:
        Console.WriteLine($"Long string: {s}");
        break;
    case null:
        Console.WriteLine("Null value");
        break;
    default:
        Console.WriteLine("Other type");
        break;
}
    

This code checks the input against several patterns to decide what to print.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

Each new pattern adds one more check to do in the worst case.

Input Size (number of patterns)Approx. Operations (pattern checks)
4Up to 4 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of patterns.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a matching pattern grows linearly with the number of patterns to check.

Common Mistake

[X] Wrong: "The switch with pattern matching checks all patterns instantly or in constant time."

[OK] Correct: The switch checks patterns one after another until it finds a match, so more patterns mean more checks.

Interview Connect

Understanding how pattern matching scales helps you explain code efficiency clearly and shows you know how language features work under the hood.

Self-Check

What if the switch used a hash-based lookup for patterns? How would the time complexity change?