0
0
Rubyprogramming~5 mins

Running scripts with ruby command - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Running scripts with ruby command
O(n)
Understanding Time Complexity

When we run Ruby scripts using the ruby command, it's helpful to know how the time it takes grows as the script processes more data.

We want to understand how the script's running time changes when the input size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    def print_numbers(n)
      i = 0
      while i < n
        puts i
        i += 1
      end
    end

    print_numbers(5)
    

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

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As n grows, the number of times the loop runs grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The script runs instantly no matter how big n is."

[OK] Correct: Each number must be printed one by one, so more numbers mean more time.

Interview Connect

Understanding how loops affect running time helps you explain your code clearly and shows you can think about efficiency.

Self-Check

"What if we changed the loop to print only even numbers up to n? How would the time complexity change?"