0
0
Rubyprogramming~5 mins

Parameters with default values in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameters with default values
O(n)
Understanding Time Complexity

Let's see how using default values for parameters affects how long a program takes to run.

We want to know if adding default values changes the work the program does as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def greet(name = "Friend")
  puts "Hello, #{name}!"
end

greet("Alice")
greet()

This code defines a method that says hello to a name, or to "Friend" if no name is given.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The method runs a simple print statement once per call.
  • How many times: Each call runs the print once; no loops or recursion inside.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 print operations
100100 print operations
10001000 print operations

Pattern observation: The work grows directly with how many times the method is called, not affected by default values.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of calls, whether or not default values are used.

Common Mistake

[X] Wrong: "Using default values makes the method slower because it has to check the defaults every time."

[OK] Correct: The check for default values is very quick and does not add extra loops or big work, so it does not change how time grows with input size.

Interview Connect

Understanding how default parameters affect time helps you explain your code clearly and shows you know what really matters for performance.

Self-Check

"What if the method had a loop inside that ran based on the parameter value? How would the time complexity change?"