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?"
Practice
readonly array in TypeScript do?Solution
Step 1: Understand the
Thereadonlykeywordreadonlykeyword before an array type means the array cannot be changed after it is created.Step 2: Effects on the array
This means you cannot add, remove, or modify elements in the array once it is set.Final Answer:
Prevents any changes to the array elements after creation -> Option DQuick Check:
readonlyarrays are immutable [OK]
- Thinking readonly only blocks length changes
- Assuming elements can be modified individually
- Confusing readonly with optional elements
Solution
Step 1: Recall the correct
In TypeScript,readonlysyntaxreadonlycomes before the array type, likereadonly number[].Step 2: Check each option
let nums: readonly number[] = [1, 2, 3]; usesreadonly number[], which is correct syntax. Others placereadonlyincorrectly.Final Answer:
let nums: readonly number[] = [1, 2, 3]; -> Option AQuick Check:
readonlybefore type [OK]
- Placing readonly after the array brackets
- Using readonly as a variable modifier
- Trying to put readonly inside the array literal
const arr: readonly string[] = ['a', 'b', 'c'];
// arr.push('d');
console.log(arr.length);Solution
Step 1: Understand the array declaration
The arrayarris declared asreadonly string[]with 3 elements: 'a', 'b', 'c'.Step 2: Check the commented out push and output
Thepushline is commented out, so it does not run. The length remains 3.Final Answer:
3 -> Option CQuick Check:
Readonly array length unchanged = 3 [OK]
- Assuming push works on readonly arrays
- Expecting length to increase despite push commented
- Confusing runtime errors with compile-time errors
const nums: readonly number[] = [1, 2, 3]; nums[0] = 10;
Solution
Step 1: Understand the readonly array behavior
The arraynumsis readonly, so its elements cannot be changed after creation.Step 2: Analyze the assignment to an element
Trying to assignnums[0] = 10causes an error because elements are read-only.Final Answer:
Cannot assign to '0' because it is a read-only property -> Option BQuick Check:
Readonly elements cannot be changed [OK]
- Thinking only array structure is readonly, not elements
- Ignoring TypeScript error messages
- Assuming semicolon missing causes error
function process(items: readonly number[]) {
// Which line is valid?
// A) items.push(5);
// B) items[0] = 10;
// C) const first = items[0];
// D) items.length = 0;
}Solution
Step 1: Understand read-only array restrictions
Read-only arrays do not allow modifying methods likepush, element assignment, or length changes.Step 2: Check each operation
Only reading elements, likeconst first = items[0];, is allowed. Others cause errors.Final Answer:
const first = items[0]; -> Option AQuick Check:
Reading elements allowed, modifying disallowed [OK]
- Trying to push or assign elements in readonly arrays
- Attempting to change array length
- Confusing read-only with mutable arrays
Ready to prove it?
Pass the test and this pattern moves unknown
