0
0
Javascriptprogramming~5 mins

Arithmetic operators in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Arithmetic operators
O(n)
Understanding Time Complexity

We want to see how the time to run arithmetic operations changes as we do more of them.

How does the number of calculations affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let sum = 0;
for (let i = 0; i < n; i++) {
  sum += i + 2 * 3 - 1;
}
// return sum; (removed return statement as it's invalid outside a function)
    

This code adds up a simple arithmetic expression for each number from 0 to n-1.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The arithmetic calculation inside the loop.
  • How many times: It runs once for each number from 0 to n-1, so n times.
How Execution Grows With Input

Each time n grows, the number of arithmetic operations grows the same amount.

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

Pattern observation: The work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Arithmetic operations inside a loop take constant time no matter how many times the loop runs."

[OK] Correct: Each arithmetic operation is fast, but doing many of them adds up, so total time grows with the number of loop runs.

Interview Connect

Understanding how simple calculations add up helps you explain how programs handle bigger data smoothly.

Self-Check

"What if we replaced the arithmetic inside the loop with another loop? How would the time complexity change?"