0
0
Typescriptprogramming~5 mins

Void type for functions in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Void type for functions
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a function with a void return type changes as input grows.

We want to know how the function's work grows with bigger inputs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function printNumbers(n: number): void {
  for (let i = 0; i < n; i++) {
    console.log(i);
  }
}
    

This function prints numbers from 0 up to n-1 and returns nothing (void).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs console.log for each number.
  • How many times: Exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

Input Size (n)Approx. Operations
1010 print actions
100100 print actions
10001000 print actions

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

Final Time Complexity

Time Complexity: O(n)

This means the function takes longer in a straight line as the input number gets bigger.

Common Mistake

[X] Wrong: "Since the function returns void, it must run instantly or have no cost."

[OK] Correct: The return type only says what the function gives back, not how long it takes. The loop still runs n times, so the time grows with n.

Interview Connect

Understanding how loops affect time, even in functions that return nothing, helps you explain your code clearly and think about efficiency.

Self-Check

"What if we changed the loop to run only half of n times? How would the time complexity change?"