0
0
Typescriptprogramming~5 mins

Boolean type behavior in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Boolean type behavior
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets longer, the program checks each Boolean one by one.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of Booleans.

Final Time Complexity

Time Complexity: O(n)

This means the time to count true values grows in a straight line as the list gets longer.

Common Mistake

[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.

Interview Connect

Understanding how simple loops over Booleans scale helps you explain basic efficiency clearly and confidently.

Self-Check

"What if we changed the array to a nested array of Booleans? How would the time complexity change?"