0
0
Rubyprogramming~5 mins

While loop in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input size grows.

Specifically, how many times does the loop run when the input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


i = 0
while i < n
  puts i
  i += 1
end

This code prints numbers from 0 up to n-1 using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As n gets bigger, the loop runs more times, growing in a straight line.

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

Pattern observation: The number of operations grows directly with n; if n doubles, operations double.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "The while loop runs a fixed number of times no matter what n is."

[OK] Correct: The loop runs once for each number up to n, so if n grows, the loop runs more times.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we changed the loop to increase i by 2 each time? How would the time complexity change?"