HTML builder example pattern in Kotlin - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that runsntimes to add paragraphs. - How many times: Exactly
ntimes, once for each paragraph.
Each time we increase n, the program adds one more paragraph, doing a similar amount of work for each.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 paragraph additions |
| 100 | About 100 paragraph additions |
| 1000 | About 1000 paragraph additions |
Pattern observation: The work grows directly in proportion to n. Double the paragraphs, double the work.
Time Complexity: O(n)
This means the time to build the HTML grows linearly as we add more paragraphs.
[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.
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.
"What if we nested another loop inside to add multiple paragraphs per body tag? How would the time complexity change?"