0
0
Kotlinprogramming~5 mins

Nested class independence from outer in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested class independence from outer
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside the countTo method that prints numbers from 1 to n.
  • How many times: It runs exactly n times, where n is the input number.
How Execution Grows With Input

As the input number n grows, the loop runs more times, increasing the work linearly.

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

Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the method grows in a straight line with the input size.

Common Mistake

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

Interview Connect

Understanding how nested classes work helps you explain code structure clearly and shows you know how different parts of code affect performance.

Self-Check

"What if the nested class accessed a list from the outer class and looped over it? How would the time complexity change?"