Tuple with fixed length and types in Typescript - Time & Space Complexity
We want to understand how the time it takes to work with a tuple changes as the tuple size changes.
Specifically, how does accessing or using a fixed-length tuple behave when the tuple size is known?
Analyze the time complexity of the following code snippet.
const tuple: [number, string, boolean] = [42, "hello", true];
function printTuple(t: [number, string, boolean]) {
console.log(t[0]);
console.log(t[1]);
console.log(t[2]);
}
printTuple(tuple);
This code defines a tuple with three fixed types and prints each element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each element of the tuple individually.
- How many times: Exactly three times, once per element.
Since the tuple length is fixed, the number of operations stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 |
Pattern observation: The operations do not increase with input size because the tuple size is fixed.
Time Complexity: O(1)
This means the time to access or use the tuple does not grow with input size; it stays constant.
[X] Wrong: "Accessing elements in a tuple takes longer as the tuple gets bigger."
[OK] Correct: Because tuples have a fixed size and known types, accessing each element is a direct operation and does not depend on input size growth.
Understanding fixed-size tuples helps you reason about predictable and constant-time operations, a useful skill when discussing data structures and performance.
"What if the tuple length was not fixed but variable? How would the time complexity change?"