Iterating collections with forEach in Kotlin - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop visits each item once. - How many times: Exactly once per item in the list.
As the list gets bigger, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[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.
Understanding how forEach scales helps you explain your code choices clearly and shows you know how loops affect performance.
"What if we nested a forEach inside another forEach? How would the time complexity change?"
Practice
forEach function do when used on a list in Kotlin?Solution
Step 1: Understand the purpose of forEach
TheforEachfunction is designed to execute a given block of code on every element in a collection.Step 2: Compare options with forEach behavior
Only It runs a block of code for each item in the list. correctly describes this behavior. Options B, C, and D describe other functions likemap,remove, andsort.Final Answer:
It runs a block of code for each item in the list. -> Option AQuick Check:
forEach = run code on each item [OK]
- Confusing forEach with map that creates new lists
- Thinking forEach modifies the list itself
- Assuming forEach sorts or filters the list
numbers using forEach in Kotlin?Solution
Step 1: Recall the correct forEach syntax
In Kotlin,forEachis called on the collection with a lambda block:collection.forEach { item -> ... }. The shorthand usesitfor the current item.Step 2: Check each option's syntax
numbers.forEach { println(it) } matches the correct syntax. forEach(numbers) { println(it) } wrongly uses forEach as a function with the list as argument. numbers.forEach(println(it)) incorrectly calls println inside forEach parentheses. numbers.forEach -> println(it) uses an invalid arrow syntax.Final Answer:
numbers.forEach { println(it) } -> Option CQuick Check:
Correct forEach syntax = numbers.forEach { println(it) } [OK]
- Calling forEach as a standalone function
- Passing println(it) directly inside forEach parentheses
- Using arrow (->) outside lambda block
val fruits = listOf("apple", "banana", "cherry")
fruits.forEach { println(it.length) }Solution
Step 1: Understand the code behavior
The listfruitscontains three strings: "apple", "banana", and "cherry". TheforEachprints the length of each string.Step 2: Calculate lengths and output format
"apple" has length 5, "banana" has length 6, "cherry" has length 6. Eachprintlnprints on a new line, so output is: 5 6 6Final Answer:
5 6 6 -> Option BQuick Check:
Print lengths with println = lines of 5,6,6 [OK]
- Assuming output is on one line separated by spaces
- Confusing string length with number of vowels
- Printing the strings instead of their lengths
val nums = listOf(1, 2, 3) nums.forEach(i -> println(i))
Solution
Step 1: Check lambda syntax in Kotlin
Kotlin uses curly braces{}for lambdas, not arrow notation like->outside braces. The arrow is used inside the lambda to separate parameters from body.Step 2: Identify the incorrect usage
The code usesi -> println(i)directly after forEach without braces, which is invalid syntax. Correct form isnums.forEach { i -> println(i) }.Final Answer:
Using arrow (->) instead of curly braces for lambda -> Option DQuick Check:
Lambda needs braces {} around arrow -> [OK]
- Using arrow notation without braces
- Confusing Kotlin lambda syntax with other languages
- Thinking val vs var affects forEach usage
nums, how can you use forEach to print only the even numbers?Solution
Step 1: Understand the condition for even numbers
An even number has zero remainder when divided by 2, soit % 2 == 0checks if a number is even.Step 2: Use if inside forEach to print only even numbers
nums.forEach { if (it % 2 == 0) println(it) } correctly uses an if statement inside the lambda to print only when the condition is true. Other options either print booleans or have incorrect syntax.Final Answer:
nums.forEach { if (it % 2 == 0) println(it) } -> Option AQuick Check:
Use if inside forEach to filter printing [OK]
- Printing boolean results instead of numbers
- Using division instead of modulo for even check
- Placing if after println causing syntax error
Ready to prove it?
Pass the test and this pattern moves unknown
