Nested class independence from outer in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code changes when using nested classes in Kotlin.
Does the nested class depend on the outer class for its speed?
Analyze the time complexity of the following code snippet.
class Outer {
class Nested {
fun countTo(n: Int) {
for (i in 1..n) {
println(i)
}
}
}
}
fun main() {
val nested = Outer.Nested()
nested.countTo(5)
}
This code defines a nested class inside an outer class and runs a simple loop inside the nested class method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the
countTomethod that prints numbers from 1 to n. - How many times: It runs exactly n times, where n is the input number.
As the input number n grows, the loop runs more times, increasing the work linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops |
| 100 | 100 loops |
| 1000 | 1000 loops |
Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the method grows in a straight line with the input size.
[X] Wrong: "The nested class slows down the code because it depends on the outer class."
[OK] Correct: The nested class here is independent and runs its own code. It does not add extra loops or slow down the process.
Understanding how nested classes work helps you explain code structure clearly and shows you know how different parts of code affect performance.
"What if the nested class accessed a list from the outer class and looped over it? How would the time complexity change?"