0
0
Kotlinprogramming~5 mins

HTML builder example pattern in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: HTML builder example pattern
O(n)
Understanding Time Complexity

We want to understand how the time it takes to build HTML grows as we add more elements using the builder pattern in Kotlin.

How does adding more nested tags affect the work the program does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

fun htmlBuilderExample(n: Int) {
    html {
        body {
            for (i in 1..n) {
                p { +"Paragraph $i" }
            }
        }
    }
}

fun html(block: Html.() -> Unit) = Html().apply(block)

class Html {
    fun body(block: Body.() -> Unit) { /* ... */ }
}

class Body {
    fun p(block: P.() -> Unit) { /* ... */ }
}

class P {
    operator fun String.unaryPlus() { /* ... */ }
}

This code builds an HTML structure with n paragraphs inside a single body tag using a builder pattern.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop that runs n times to add paragraphs.
  • How many times: Exactly n times, once for each paragraph.
How Execution Grows With Input

Each time we increase n, the program adds one more paragraph, doing a similar amount of work for each.

Input Size (n)Approx. Operations
10About 10 paragraph additions
100About 100 paragraph additions
1000About 1000 paragraph additions

Pattern observation: The work grows directly in proportion to n. Double the paragraphs, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the HTML grows linearly as we add more paragraphs.

Common Mistake

[X] Wrong: "Adding more paragraphs won't affect the time much because it's just building strings."

[OK] Correct: Each paragraph requires a separate step in the loop, so more paragraphs mean more work, increasing time linearly.

Interview Connect

Understanding how loops affect time helps you explain how your code scales when building structures like HTML. This skill shows you can think about efficiency clearly.

Self-Check

"What if we nested another loop inside to add multiple paragraphs per body tag? How would the time complexity change?"