0
0
R Programmingprogramming~5 mins

Repeat loop with break in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Repeat loop with break
O(n)
Understanding Time Complexity

We want to understand how long a repeat loop with a break runs as the input size changes.

Specifically, how many times does the loop repeat before it stops?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


i <- 1
repeat {
  if (i > n) {
    break
  }
  print(i)
  i <- i + 1
}
    

This code counts from 1 up to n, printing each number, then stops.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As n gets bigger, the loop runs more times, directly matching n.

Input Size (n)Approx. Operations
10About 10 repeats
100About 100 repeats
1000About 1000 repeats

Pattern observation: The number of repeats grows evenly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the size of n.

Common Mistake

[X] Wrong: "The repeat loop always runs forever because it has no set end."

[OK] Correct: The break condition stops the loop once i passes n, so it does end after n repeats.

Interview Connect

Understanding how loops with breaks behave helps you explain how code runs step-by-step and how long it takes.

Self-Check

"What if the break condition checked for i > n^2 instead? How would the time complexity change?"