0
0
Typescriptprogramming~5 mins

Callback function types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Callback function types
O(n)
Understanding Time Complexity

When using callback functions, it is important to know how the program's running time changes as the input grows.

We want to see how many times the callback runs and how that affects overall speed.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processItems(items: number[], callback: (item: number) => void): void {
  for (const item of items) {
    callback(item);
  }
}

const numbers = [1, 2, 3, 4, 5];
processItems(numbers, (num) => console.log(num * 2));
    

This code runs a callback on each item in an array, doing something with each number.

Identify Repeating Operations
  • Primary operation: The for-loop that goes through each item in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

As the number of items grows, the callback runs more times, so the total work grows too.

Input Size (n)Approx. Operations
1010 callback calls
100100 callback calls
10001000 callback calls

Pattern observation: The work grows directly with the number of items, doubling the items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "The callback runs only once, so time is constant."

[OK] Correct: The callback runs once for each item, so more items mean more calls and more time.

Interview Connect

Understanding how callbacks affect time helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if the callback itself contains a loop over the entire array? How would the time complexity change?"