0
0
PowerShellscripting~5 mins

Switch with wildcard and regex in PowerShell - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Switch with wildcard and regex
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a switch statement with wildcard and regex patterns changes as we add more items to check.

Specifically, how does the number of checks grow when the input list gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$samples = @('apple', 'banana', 'cherry', 'date')
foreach ($item in $samples) {
  switch -Wildcard ($item) {
    'a*' { Write-Output "Starts with a: $item" }
    '*n*' { Write-Output "Contains n: $item" }
    default { Write-Output "No match: $item" }
  }
}
    

This code checks each item in a list against wildcard patterns using a switch statement and prints a message based on the match.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each item in the list and checking it against each switch pattern.
  • How many times: For each item, the switch checks patterns one by one until a match is found or all patterns are checked.
How Execution Grows With Input

As the list of items grows, the number of checks grows roughly in proportion to the number of items times the number of patterns.

Input Size (n)Approx. Operations
10About 10 times the number of patterns
100About 100 times the number of patterns
1000About 1000 times the number of patterns

Pattern observation: The total checks grow linearly as the number of items increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of items you check.

Common Mistake

[X] Wrong: "Using wildcard or regex makes the switch run in constant time regardless of input size."

[OK] Correct: Each item still needs to be checked against each pattern, so time grows with the number of items.

Interview Connect

Understanding how pattern matching scales helps you write scripts that stay fast even with bigger data. This skill shows you can think about efficiency, not just correctness.

Self-Check

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