0
0
Kotlinprogramming~5 mins

Iterating collections with forEach in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterating collections with forEach
O(n)
Understanding Time Complexity

When we use forEach 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.


val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { number ->
    println(number)
}
    

This code goes through each number in the list and prints it out.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The forEach loop visits each item once.
  • How many times: Exactly once per 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.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using forEach is slower than a regular for loop because it has extra overhead."

[OK] Correct: Both do the same number of steps over the list. The difference is tiny and does not change how time grows with list size.

Interview Connect

Understanding how forEach scales helps you explain your code choices clearly and shows you know how loops affect performance.

Self-Check

"What if we nested a forEach inside another forEach? How would the time complexity change?"