Null and undefined types in Typescript - Time & Space Complexity
We want to understand how checking for null or undefined values affects the speed of a program.
Specifically, how does the time to run grow when we check many values for null or undefined?
Analyze the time complexity of the following code snippet.
function countValid(values: (string | null | undefined)[]): number {
let count = 0;
for (const val of values) {
if (val !== null && val !== undefined) {
count++;
}
}
return count;
}
This code counts how many items in an array are not null or undefined.
- Primary operation: Looping through each item in the array once.
- How many times: Exactly once for every item in the input array.
As the number of items grows, the time to check each item grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "Checking for null or undefined is slow and adds extra loops."
[OK] Correct: The check happens inside the same loop, so it does not add extra loops or multiply the time.
Understanding how simple checks inside loops affect performance helps you write clear and efficient code.
"What if we nested another loop inside to check each character of each string? How would the time complexity change?"