0
0
Kotlinprogramming~5 mins

StringBuilder for performance in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: StringBuilder for performance
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we add a number, the work grows a little, but StringBuilder helps keep it steady.

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

Pattern observation: The work grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the string grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how StringBuilder helps with performance shows you know how to handle growing data efficiently, a useful skill in many coding tasks.

Self-Check

"What if we used regular string concatenation (+) inside the loop instead of StringBuilder? How would the time complexity change?"