Multiline strings with trimIndent in Kotlin - Time & Space Complexity
We want to understand how the time to process multiline strings with trimIndent changes as the string size grows.
How does the trimming operation scale when the string has more lines?
Analyze the time complexity of the following code snippet.
val text = """
line one
line two
line three
""".trimIndent()
println(text)
This code creates a multiline string and removes common leading spaces from each line using trimIndent.
- Primary operation: The function scans each line of the string to find the smallest indent and then removes that indent from all lines.
- How many times: It processes each line twice: once to find the indent, once to trim it.
As the number of lines increases, the trimming work grows roughly in proportion to the number of lines.
| Input Size (n lines) | Approx. Operations |
|---|---|
| 10 | About 20 line checks (2 per line) |
| 100 | About 200 line checks |
| 1000 | About 2000 line checks |
Pattern observation: The work doubles if the number of lines doubles, showing a steady growth.
Time Complexity: O(n)
This means the time to trim indentation grows linearly with the number of lines in the string.
[X] Wrong: "trimIndent runs instantly no matter how big the string is."
[OK] Correct: The function must check each line to find and remove indentation, so more lines mean more work.
Understanding how string operations scale helps you reason about performance in real apps, especially when handling large text data.
"What if we used trimMargin instead of trimIndent? How would the time complexity change?"