Generic functions with arrays in Typescript - Time & Space Complexity
When using generic functions with arrays, it's important to know how the time to run the function changes as the array grows.
We want to find out how many steps the function takes depending on the size of the input array.
Analyze the time complexity of the following code snippet.
function getFirstElement<T>(arr: T[]): T | undefined {
if (arr.length === 0) return undefined;
return arr[0];
}
const numbers = [1, 2, 3, 4, 5];
const first = getFirstElement(numbers);
This function returns the first element of any array passed to it, using a generic type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the first element of the array.
- How many times: Exactly once, no loops or repeated steps.
Since the function only looks at the first element, the number of steps does not grow with the array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work stays the same no matter how big the array is.
Time Complexity: O(1)
This means the function takes the same amount of time regardless of the array size.
[X] Wrong: "Because the input array can be very large, the function must take longer to run."
[OK] Correct: The function only looks at the first element once, so the size of the array does not affect the time it takes.
Understanding how generic functions behave with arrays helps you explain your code clearly and shows you know how to reason about performance.
"What if the function returned the last element instead of the first? How would the time complexity change?"