0
0
Kotlinprogramming~5 mins

For loop over collections in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop over collections
O(n)
Understanding Time Complexity

When we use a for loop to go through a collection, we want to know how the time it takes changes as the collection grows.

We ask: How does the work increase when the list gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun printAllNames(names: List) {
    for (name in names) {
        println(name)
    }
}
    

This code goes through each name in the list and prints it out one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that visits each item in the list.
  • How many times: Exactly once for each item in the list.
How Execution Grows With Input

As the list gets bigger, the number of print actions grows the same way.

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

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the size of the list.

Common Mistake

[X] Wrong: "The loop runs faster because it just prints simple text."

[OK] Correct: The speed depends on how many times the loop runs, not what it does inside. Even simple actions add up when repeated many times.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.

Self-Check

"What if we nested another for loop inside this one to print pairs of names? How would the time complexity change?"