0
0
Kotlinprogramming~5 mins

Inner class access to outer members in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Inner class access to outer members
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when an inner class accesses members of its outer class.

We want to know how the number of steps grows as the input size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Outer(val numbers: List<Int>) {
    inner class Inner {
        fun sum(): Int {
            var total = 0
            for (num in numbers) {
                total += num
            }
            return total
        }
    }
}

fun main() {
    val outer = Outer(listOf(1, 2, 3, 4, 5))
    val inner = outer.Inner()
    println(inner.sum())
}

This code defines an outer class holding a list of numbers and an inner class that sums those numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of numbers inside the inner class's sum() function.
  • How many times: Once for each number in the list (n times).
How Execution Grows With Input

As the list gets bigger, the sum function takes longer because it adds each number one by one.

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

Pattern observation: The time grows directly with the number of items; doubling the list doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the sum grows in a straight line with the size of the list.

Common Mistake

[X] Wrong: "Accessing outer class members from the inner class adds extra loops or slows down the code significantly."

[OK] Correct: Accessing outer members is direct and does not add extra loops; the main time cost is still just looping through the list once.

Interview Connect

Understanding how inner classes access outer members helps you explain code structure and performance clearly, a useful skill in many coding discussions.

Self-Check

What if the inner class stored a copy of the list instead of accessing the outer class's list directly? How would the time complexity change?