0
0
Typescriptprogramming~5 mins

Null and undefined types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Null and undefined types
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each item in the array once.
  • How many times: Exactly once for every item in the input array.
How Execution Grows With Input

As the number of items grows, the time to check each item grows the same way.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The number of checks grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input list gets bigger.

Common Mistake

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

Interview Connect

Understanding how simple checks inside loops affect performance helps you write clear and efficient code.

Self-Check

"What if we nested another loop inside to check each character of each string? How would the time complexity change?"