Control flow analysis behavior in Typescript - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | Up to 10 checks and additions |
| 100 | Up to 100 checks and additions |
| 1000 | Up to 1000 checks and additions |
Pattern observation: The work grows roughly in a straight line with input size until a stopping point.
Time Complexity: O(n)
This means the program's steps grow directly with the number of items it checks.
[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.
Understanding how control flow affects steps helps you explain how your code behaves with different inputs clearly and confidently.
"What if we changed the break to continue? How would the time complexity change?"