Read-only arrays in Typescript - Time & Space Complexity
We want to understand how the time to work with read-only arrays changes as the array gets bigger.
How does the program's speed change when we only read from an array without changing it?
Analyze the time complexity of the following code snippet.
function sumReadOnlyArray(arr: readonly number[]): number {
let total = 0;
for (const num of arr) {
total += num;
}
return total;
}
This code adds up all numbers in a read-only array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array once.
- How many times: Exactly once for each element in the array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The number of operations grows directly with the size of the array. Double the size, double the work.
Time Complexity: O(n)
This means the time to sum the array grows in a straight line with the number of elements.
[X] Wrong: "Because the array is read-only, accessing elements is faster and takes constant time overall."
[OK] Correct: Even if the array cannot be changed, you still need to look at each element one by one to sum them, so the time grows with the number of elements.
Understanding how read-only arrays behave helps you explain why some operations are fast or slow, which is a useful skill when discussing code efficiency in interviews.
"What if we changed the array to a nested array and summed all numbers inside? How would the time complexity change?"