0
0
Kotlinprogramming~5 mins

Inner classes and nested classes in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Inner classes and nested classes
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code with inner and nested classes changes as the input grows.

We want to know which parts of the code repeat and how that affects the total work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Outer {
    private val numbers = listOf(1, 2, 3, 4, 5)

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

    class Nested {
        fun greet() = "Hello"
    }
}

This code defines an outer class with an inner class that sums a list and a nested class that just says hello.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop inside the Inner.sum() method that goes through the list numbers.
  • How many times: It runs once for each item in the list, so as many times as the list size.
How Execution Grows With Input

As the list size grows, the loop inside Inner.sum() runs more times, adding up numbers one by one.

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

Pattern observation: The work grows directly with the list size. Double the list, double the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The nested class Nested affects the time it takes to sum the numbers."

[OK] Correct: The nested class Nested does not access the list or run loops, so it does not add to the time complexity of summing.

Interview Connect

Understanding how inner and nested classes work helps you explain how your code runs and grows, a skill that shows you think clearly about your programs.

Self-Check

"What if the Inner class stored the sum result and reused it instead of looping every time? How would the time complexity change?"