Switch with wildcard and regex in PowerShell - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | About 10 times the number of patterns |
| 100 | About 100 times the number of patterns |
| 1000 | About 1000 times the number of patterns |
Pattern observation: The total checks grow linearly as the number of items increases.
Time Complexity: O(n)
This means the time to run grows directly with the number of items you check.
[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.
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.
"What if we added more patterns inside the switch? How would the time complexity change?"