0
0
Typescriptprogramming~5 mins

Control flow analysis behavior in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Control flow analysis behavior
O(n)
Understanding Time Complexity

We want to understand how the program's steps grow as the input changes when using control flow analysis.

How does the program decide which parts to run and how often?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processItems(items: number[]): number {
  let total = 0;
  for (const item of items) {
    if (item > 0) {
      total += item;
    } else {
      break;
    }
  }
  return total;
}
    

This code sums positive numbers in an array until it finds a non-positive number, then stops.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array items one by one.
  • How many times: Up to the first non-positive number or the whole array length.
How Execution Grows With Input

Execution grows with the number of positive items before a non-positive one or the full array length if none found.

Input Size (n)Approx. Operations
10Up to 10 checks and additions
100Up to 100 checks and additions
1000Up to 1000 checks and additions

Pattern observation: The work grows roughly in a straight line with input size until a stopping point.

Final Time Complexity

Time Complexity: O(n)

This means the program's steps grow directly with the number of items it checks.

Common Mistake

[X] Wrong: "The loop always runs for the entire array length no matter what."

[OK] Correct: The loop stops early when it finds a non-positive number, so it may run less than the full length.

Interview Connect

Understanding how control flow affects steps helps you explain how your code behaves with different inputs clearly and confidently.

Self-Check

"What if we changed the break to continue? How would the time complexity change?"