0
0
Kotlinprogramming~5 mins

For loop with index (withIndex) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop with index (withIndex)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the list gets bigger, the number of steps grows directly with the number of items.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The steps increase evenly as the list size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items.

Common Mistake

[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.

Interview Connect

Knowing how loops with indexes scale helps you explain your code clearly and shows you understand how programs handle data efficiently.

Self-Check

"What if we nested another loop inside this one that also goes through the list? How would the time complexity change?"