0
0
Kotlinprogramming~5 mins

Repeat function for simple repetition in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Repeat function for simple repetition
O(n)
Understanding Time Complexity

We want to understand how the time taken by Kotlin's repeat function changes as we repeat an action more times.

The question is: How does the number of repetitions affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun printHello(times: Int) {
    repeat(times) {
        println("Hello")
    }
}

printHello(5)
    

This code prints "Hello" a number of times given by times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The repeat function runs the print statement multiple times.
  • How many times: Exactly times times, as given by the input.
How Execution Grows With Input

Each time we increase times, the print action happens that many more times.

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

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

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of repetitions, the total work roughly doubles too.

Common Mistake

[X] Wrong: "The repeat function runs instantly no matter how many times."

[OK] Correct: Each repetition runs the code inside once, so more repetitions mean more work and more time.

Interview Connect

Understanding how simple loops like repeat scale helps you explain how programs handle repeated tasks efficiently.

Self-Check

"What if we nested one repeat inside another? How would the time complexity change?"