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?"
Practice
What is the main purpose of using a generic function with <T> in TypeScript when working with arrays?
Solution
Step 1: Understand generic type
The generic type<T><T>allows a function to accept any type, making it reusable for different data types.Step 2: Apply to arrays
Using<T>with arrays means the function can handle arrays of numbers, strings, or any other type without rewriting the function.Final Answer:
To allow the function to work with arrays of any type without rewriting code. -> Option AQuick Check:
Generic<T>= reusable for any type [OK]
<T> means any type works [OK]- Thinking generic restricts to one type
- Assuming generic converts types
- Believing generic improves speed only
Which of the following is the correct syntax to declare a generic function firstElement that returns the first element of an array of any type?
function firstElement(____): T | undefined {
return arr[0];
}Solution
Step 1: Identify generic function syntax
Generic functions declare the type parameter before the argument list, likefunction fnName<T>(args).Step 2: Match syntax to example
The correct syntax isfunction firstElement<T>(arr: T[]): T | undefinedto accept an array of typeT.Final Answer:
<T>(arr: T[]) -> Option CQuick Check:
Generic syntax = <T>(args) [OK]
- Placing
<T>after parameters - Omitting
<T>entirely - Using incorrect parameter types
What will be the output of the following TypeScript code?
function getLastElement<T>(arr: T[]): T | undefined {
return arr.length ? arr[arr.length - 1] : undefined;
}
const nums = [10, 20, 30];
const result = getLastElement(nums);
console.log(result);Solution
Step 1: Understand function behavior
The function returns the last element if the array is not empty; otherwise, it returns undefined.Step 2: Apply to given array
The arraynumsis [10, 20, 30], so the last element is 30, which is returned and logged.Final Answer:
30 -> Option AQuick Check:
Last element of [10,20,30] = 30 [OK]
- Returning first element instead
- Ignoring empty array case
- Expecting error due to generics
Identify the error in this generic function and select the corrected version:
function wrapInArray<T>(item: T): T[] {
return item;
}Solution
Step 1: Analyze function return type
The function promises to return an array of typeT[], but returnsitemwhich is typeT, not an array.Step 2: Fix return statement
Wrappingitemin square brackets[item]creates an array containing the item, matching the return type.Final Answer:
Change return to[item]to return an array containing the item. -> Option BQuick Check:
Return array by wrapping item in [] [OK]
- Returning item directly instead of array
- Changing parameter type unnecessarily
- Removing generics without reason
You want to create a generic function filterNonEmpty that takes an array of any type T and returns a new array excluding null and undefined values. Which implementation correctly uses generics and array filtering?
Solution
Step 1: Define input and output types
The input array can containT,null, orundefined, so its type is(T | null | undefined)[]. The output should be onlyT[].Step 2: Filter out
Usingnullandundefinedfilter(item => item != null)removes bothnullandundefinedvalues safely.Final Answer:
function filterNonEmpty<T>(arr: (T | null | undefined)[]): T[] { return arr.filter(item => item != null); } -> Option DQuick Check:
Filter null/undefined from mixed array [OK]
- Not typing input to include null/undefined
- Returning wrong output type
- Using strict !== null only, missing undefined
Ready to prove it?
Pass the test and this pattern moves unknown
