For loop with index (withIndex) in Kotlin - Time & Space Complexity
We want to understand how the time needed to run a for loop with index changes as the list size grows.
How does the number of steps grow when we loop over more items?
Analyze the time complexity of the following code snippet.
val items = listOf("apple", "banana", "cherry")
for ((index, item) in items.withIndex()) {
println("Item #$index is $item")
}
This code loops through a list of items, printing each item with its position number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for each item in the list.
As the list gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase evenly as the list size increases.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Using withIndex makes the loop slower because it adds extra work."
[OK] Correct: The withIndex function just pairs each item with its index without extra loops, so it still goes through the list only once.
Knowing how loops with indexes scale helps you explain your code clearly and shows you understand how programs handle data efficiently.
"What if we nested another loop inside this one that also goes through the list? How would the time complexity change?"
Practice
withIndex() function do in a Kotlin for loop?Solution
Step 1: Understand the purpose of
ThewithIndex()withIndex()function returns an iterable of pairs containing the index and the value of each element in the collection.Step 2: Identify what the loop receives
UsingwithIndex()in aforloop allows access to both the position (index) and the element (value) simultaneously.Final Answer:
It provides both the index and the value of each element during iteration. -> Option CQuick Check:
withIndex() = index + value [OK]
- Thinking it sorts or filters the list
- Assuming it reverses the collection
- Confusing index with value only
items with index in Kotlin?Solution
Step 1: Recall Kotlin destructuring syntax in loops
Kotlin allows destructuring pairs using parentheses in theforloop header, likefor ((index, value) in ...).Step 2: Match syntax with
The correct syntax useswithIndex()items.withIndex()and destructures the pair intoindexandvalue.Final Answer:
for ((index, value) in items.withIndex()) { /* code */ } -> Option AQuick Check:
Destructure pairs with (index, value) [OK]
- Omitting parentheses around (index, value)
- Using semicolon instead of comma
- Missing 'in' keyword
val data = listOf("apple", "banana", "cherry")
for ((i, v) in data.withIndex()) {
println("$i: $v")
}Solution
Step 1: Understand the list and loop
The list contains three fruits: "apple", "banana", "cherry". The loop useswithIndex()to get index and value.Step 2: Trace the loop output
Each iteration prints the index and value separated by colon and space. Indices start at 0.Final Answer:
0: apple 1: banana 2: cherry -> Option AQuick Check:
Index starts at 0, prints index: value [OK]
- Assuming index starts at 1
- Swapping index and value in output
- Expecting error from destructuring
val numbers = arrayOf(10, 20, 30)
for (i, num in numbers.withIndex()) {
println("$i -> $num")
}Solution
Step 1: Check for correct destructuring syntax
In Kotlin, destructuring pairs in a for loop requires parentheses:for ((i, num) in ...).Step 2: Verify other parts of the code
UsingwithIndex()on arrays is valid. The println syntax and variable names are correct.Final Answer:
Missing parentheses around (i, num) in the for loop. -> Option BQuick Check:
Destructure pairs with parentheses [OK]
- Omitting parentheses in destructuring
- Thinking withIndex() doesn't work on arrays
- Misreading println syntax
tables = listOf("users", "orders", "products"), how can you create a map of index to table name using a Kotlin for loop with withIndex()?Solution
Step 1: Understand the goal
We want a map where keys are indices (Int) and values are table names (String).Step 2: Use withIndex() to get index and value
Loop overtables.withIndex()and assignmap[i] = tto build the map correctly.Final Answer:
val map = mutableMapOf() for ((i, t) in tables.withIndex()) { map[i] = t } -> Option DQuick Check:
Index to value mapping with withIndex() [OK]
- Swapping key and value types in map
- Not destructuring with parentheses
- Using wrong loop variable types
Ready to prove it?
Pass the test and this pattern moves unknown
