StringBuilder for performance in Kotlin - Time & Space Complexity
When building strings repeatedly, the way we add pieces affects how long it takes.
We want to see how using StringBuilder changes the work as the string grows.
Analyze the time complexity of the following code snippet.
fun buildString(n: Int): String {
val sb = StringBuilder()
for (i in 1..n) {
sb.append(i)
}
return sb.toString()
}
This code adds numbers from 1 to n into a StringBuilder, then returns the combined string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Appending a number to the StringBuilder inside a loop.
- How many times: Exactly n times, once for each number from 1 to n.
Each time we add a number, the work grows a little, but StringBuilder helps keep it steady.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends |
| 100 | About 100 appends |
| 1000 | About 1000 appends |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to build the string grows in a straight line as the input size grows.
[X] Wrong: "Using StringBuilder is slow because it copies the whole string every time we add something."
[OK] Correct: StringBuilder keeps extra space and adds new parts without copying everything each time, so it stays fast.
Understanding how StringBuilder helps with performance shows you know how to handle growing data efficiently, a useful skill in many coding tasks.
"What if we used regular string concatenation (+) inside the loop instead of StringBuilder? How would the time complexity change?"
Practice
StringBuilder in Kotlin when combining many strings?Solution
Step 1: Understand string concatenation cost
Regular string concatenation creates new strings each time, which is slow.Step 2: Role of StringBuilder
StringBuilder appends strings without creating new copies each time, improving speed.Final Answer:
It improves performance by reducing the number of string copies. -> Option DQuick Check:
StringBuilder reduces copies [OK]
- Thinking StringBuilder sorts strings
- Assuming it changes string case automatically
- Believing it stores strings externally
StringBuilder and add text in Kotlin?Solution
Step 1: Check StringBuilder creation
Creating with StringBuilder() is correct syntax.Step 2: Identify correct method to add text
The method to add text isappend(), notadd()orinsert()with a string argument.Final Answer:
val sb = StringBuilder(); sb.append("Hello") -> Option BQuick Check:
Use append() to add text [OK]
- Using add() instead of append()
- Using insert() incorrectly
- Passing strings to insert() without index
val sb = StringBuilder()
sb.append("Hi")
sb.append(", ")
sb.append("there!")
println(sb.toString())Solution
Step 1: Trace each append call
First append adds "Hi", second adds ", ", third adds "there!".Step 2: Combine all appended strings
Combined string is "Hi, there!" exactly as appended.Final Answer:
Hi, there! -> Option AQuick Check:
Appended strings combined [OK]
- Missing spaces in appended strings
- Forgetting to call toString()
- Assuming append adds spaces automatically
StringBuilder:
val sb = StringBuilder()
sb.append("Hello")
sb.append(123)
println(sb)Solution
Step 1: Check append usage
append can accept integers and converts them to string automatically, so no error here.Step 2: Check printing StringBuilder directly
Printing StringBuilder object directly calls its toString() method, so it prints the content correctly; no error here either.Step 3: Re-examine options
Actually, printing sb directly works fine in Kotlin, so no error. The code is correct.Final Answer:
No error; code runs and prints Hello123 -> Option CQuick Check:
Printing StringBuilder directly works [OK]
- Thinking append can't take integers
- Assuming toString() is mandatory for printing
- Believing append needs two arguments
StringBuilder efficiently. Which code snippet correctly avoids adding an extra comma at the end?Solution
Step 1: Analyze each option for trailing comma
val sb = StringBuilder() for (i in 1..5) { sb.append(i).append(",") } sb.toString() adds comma after every number, including last, causing extra comma.Step 2: Check conditional comma addition
val sb = StringBuilder() for (i in 1..5) { if (i > 0) sb.append(i).append(",") else sb.append(i) } sb.toString() tries to avoid comma on last number by if-else, but condition i > 0 is always true, so always appends comma after each number, causing trailing comma.Step 3: Verify correct conditional append
val sb = StringBuilder() for (i in 1..5) { sb.append(i) if (i != 5) sb.append(",") } sb.toString() appends number first, then adds comma only if not last number, correctly avoiding trailing comma.Step 4: Check the remove prefix method
val sb = StringBuilder() for (i in 1..5) { sb.append(i) sb.append(",") } sb.toString().removePrefix(",") appends comma always, then removes prefix "," from start (which doesn't exist), leaving trailing comma.Final Answer:
val sb = StringBuilder() for (i in 1..5) { sb.append(i) if (i != 5) sb.append(",") } sb.toString() -> Option AQuick Check:
Append comma only if not last [OK]
- Adding comma after every item including last
- Appending number twice in conditional branches
- Removing suffix after building string instead of conditional append
Ready to prove it?
Pass the test and this pattern moves unknown
