0
0
Rubyprogramming~5 mins

Arithmetic operators in Ruby - Time & Space Complexity

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

When we use arithmetic operators in code, it is helpful to know how the time to run the code changes as the input size grows.

We want to find out how the number of calculations grows when we do arithmetic operations on different amounts of data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


numbers = [1, 2, 3, 4, 5]
result = []
numbers.each do |num|
  doubled = num * 2
  result << doubled
end
    

This code takes a list of numbers, doubles each number using multiplication, and stores the results in a new list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Multiplying each number by 2 inside a loop.
  • How many times: Once for each number in the list.
How Execution Grows With Input

As the list gets bigger, the number of multiplications grows in the same way.

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

Pattern observation: The number of operations grows directly with the size of the input list.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input list gets bigger.

Common Mistake

[X] Wrong: "Multiplying numbers takes longer when the numbers themselves are bigger."

[OK] Correct: The time to multiply is generally considered constant for typical integer sizes in programming, so what matters is how many numbers you multiply.

Interview Connect

Understanding how simple arithmetic inside loops affects time helps you explain how your code will behave with bigger data, a skill that shows clear thinking in interviews.

Self-Check

"What if we changed the code to multiply each number by every other number in the list? How would the time complexity change?"