0
0
Typescriptprogramming~5 mins

Generic function syntax in Typescript - Time & Space Complexity

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

We want to see how the time it takes to run a generic function changes as the input size grows.

How does the function's work increase when we give it bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function identity<T>(items: T[]): T[] {
  return items.map(item => item);
}

const numbers = [1, 2, 3, 4, 5];
const result = identity(numbers);
    

This function takes an array of any type and returns a new array with the same items.

Identify Repeating Operations
  • Primary operation: The map method loops through each item in the array.
  • How many times: Once for every item in the input array.
How Execution Grows With Input

As the input array gets bigger, the function does more work by visiting each item once.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Generic functions are slower because they handle any type."

[OK] Correct: The generic part only affects types at compile time, not how many steps the function takes at run time.

Interview Connect

Understanding how generic functions behave helps you explain your code clearly and shows you know how input size affects performance.

Self-Check

What if we changed the function to use a nested loop inside the map? How would the time complexity change?