0
0
Typescriptprogramming~5 mins

Number type behavior in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Number type behavior
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of items grows, the total additions grow at the same pace.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to add numbers grows in a straight line with how many numbers there are.

Common Mistake

[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.

Interview Connect

Understanding how simple number operations scale helps you explain performance clearly and shows you know how code behaves with bigger data.

Self-Check

"What if we used nested loops to add numbers in pairs? How would the time complexity change?"