Enum entries iteration in Kotlin - Time & Space Complexity
When we loop through all entries of an enum, we want to know how the time needed changes as the number of entries grows.
We ask: How does the work grow when the enum has more items?
Analyze the time complexity of the following code snippet.
enum class Color {
RED, GREEN, BLUE, YELLOW
}
fun printColors() {
for (color in Color.values()) {
println(color)
}
}
This code loops through all enum entries and prints each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all enum entries using
Color.values(). - How many times: Once for each enum entry, so as many times as there are entries.
As the number of enum entries grows, the loop runs once per entry, so the work grows directly with the number of entries.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 print operations |
| 100 | About 100 print operations |
| 1000 | About 1000 print operations |
Pattern observation: The work increases evenly as the number of enum entries increases.
Time Complexity: O(n)
This means the time grows in a straight line with the number of enum entries.
[X] Wrong: "Looping over enum entries is constant time because enums are fixed."
[OK] Correct: Even though enums have fixed entries, the loop still runs once per entry, so time grows with the number of entries.
Understanding how looping over enum entries scales helps you explain performance clearly and shows you know how to analyze simple loops well.
"What if we nested another loop inside to compare each enum entry with every other? How would the time complexity change?"