Boolean type behavior in Typescript - Time & Space Complexity
We want to understand how the time it takes to work with Boolean values changes as we use more of them.
How does the program's work grow when handling many Boolean values?
Analyze the time complexity of the following code snippet.
function countTrue(values: boolean[]): number {
let count = 0;
for (const val of values) {
if (val) {
count++;
}
}
return count;
}
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 once.
- How many times: Exactly once for each item in the input list.
As the list gets longer, the program checks each Boolean one by one.
| 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 Booleans is instant and does not depend on list size."
[OK] Correct: Even though each check is quick, you must check every item, so more items mean more total work.
Understanding how simple loops over Booleans scale helps you explain basic efficiency clearly and confidently.
"What if we changed the array to a nested array of Booleans? How would the time complexity change?"