Number type behavior in Typescript - Time & Space Complexity
When working with numbers in TypeScript, it's helpful to know how operations on numbers behave as the input size changes.
We want to see how the time to do number operations grows when we do many calculations.
Analyze the time complexity of the following code snippet.
function sumNumbers(numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
This code adds up all numbers in an array and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the total inside a loop.
- How many times: Once for each number in the input array.
As the number of items grows, the total additions grow at the same pace.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line with how many numbers there are.
[X] Wrong: "Adding numbers is always instant, so time doesn't grow with input size."
[OK] Correct: Even though each addition is fast, doing many additions one after another takes more time as the list grows.
Understanding how simple number operations scale helps you explain performance clearly and shows you know how code behaves with bigger data.
"What if we used nested loops to add numbers in pairs? How would the time complexity change?"