Boolean values in PowerShell - Time & Space Complexity
We want to see how the time it takes to run a script with Boolean values changes as we work with more data.
Specifically, we ask: How does the script's work grow when checking many Boolean values?
Analyze the time complexity of the following code snippet.
# Create an array of Boolean values
$boolArray = @( $true, $false, $true, $false ) * 1000
# Count how many are True
$countTrue = 0
foreach ($value in $boolArray) {
if ($value) {
$countTrue++
}
}
Write-Output $countTrue
This code counts how many True values are in a list of Booleans.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each Boolean in the array.
- How many times: Once for every item in the array.
As the list of Booleans gets bigger, the script checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of Booleans.
Time Complexity: O(n)
This means the time to count True values grows in a straight line as the list gets longer.
[X] Wrong: "Checking Boolean values is instant and does not depend on list size."
[OK] Correct: Even though each check is fast, the script must check every item, so more items mean more total work.
Understanding how simple loops over Boolean values scale helps you explain how scripts handle data efficiently in real tasks.
"What if we used nested loops to compare each Boolean with every other Boolean? How would the time complexity change?"