0
0
Typescriptprogramming~5 mins

Nullish coalescing with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nullish coalescing with types
O(n)
Understanding Time Complexity

We want to understand how fast code runs when using nullish coalescing with types in TypeScript.

Specifically, how does the number of steps change as input size grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function getValue(input: string | null | undefined): string {
  return input ?? "default";
}

const results = [];
for (let i = 0; i < n; i++) {
  results.push(getValue(null));
}
    

This code uses nullish coalescing to provide a default string when input is null or undefined, repeated n times.

Identify Repeating Operations
  • Primary operation: The loop runs n times, calling getValue each time.
  • How many times: Exactly n times, where n is the input size.
How Execution Grows With Input

Each call to getValue is very fast and constant time, but we do it n times in the loop.

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

Pattern observation: The total work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Nullish coalescing makes the code run instantly regardless of input size."

[OK] Correct: Even though each check is quick, doing it many times adds up linearly with input size.

Interview Connect

Understanding how simple operations inside loops add up helps you explain performance clearly in interviews.

Self-Check

"What if we replaced the loop with a recursive call that processes the input n times? How would the time complexity change?"