0
0
Typescriptprogramming~5 mins

Generic array syntax in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic array syntax
O(n)
Understanding Time Complexity

We want to understand how the time it takes to work with generic arrays changes as the array grows.

How does the number of steps grow when we use generic arrays in TypeScript?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function printItems<T>(items: T[]): void {
  for (const item of items) {
    console.log(item);
  }
}

const numbers: number[] = [1, 2, 3, 4, 5];
printItems(numbers);
    

This code prints each item in a generic array, showing how generic array syntax works in TypeScript.

Identify Repeating Operations
  • Primary operation: Looping through each element of the array.
  • How many times: Once for each item in the array (n times).
How Execution Grows With Input

As the array gets bigger, the number of steps grows directly with the number of items.

Input Size (n)Approx. Operations
1010 steps (print 10 items)
100100 steps (print 100 items)
10001000 steps (print 1000 items)

Pattern observation: The steps increase evenly as the array size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to print items grows in direct proportion to the number of items in the array.

Common Mistake

[X] Wrong: "Using generic arrays makes the code slower because of extra type checks at runtime."

[OK] Correct: TypeScript types are erased during compilation, so generics do not add runtime cost or slow down loops.

Interview Connect

Understanding how loops over generic arrays behave helps you explain performance clearly and write efficient code in interviews.

Self-Check

"What if we changed the loop to a nested loop over two generic arrays? How would the time complexity change?"