String type and immutability in Kotlin - Time & Space Complexity
We want to understand how working with strings affects the time it takes for a program to run.
Specifically, how does changing or combining strings grow in cost as the strings get bigger?
Analyze the time complexity of the following code snippet.
fun buildString(n: Int): String {
var result = ""
for (i in 1..n) {
result += "a"
}
return result
}
This code creates a string by adding the letter "a" one by one, n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a character to the string inside the loop.
- How many times: The loop runs n times, each time creating a new string.
Each time we add a character, the program copies the whole string so far and adds one more character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5,050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than n; it grows roughly like the square of n.
Time Complexity: O(n²)
This means the time to build the string grows very quickly as the string gets longer, because each addition copies the whole string again.
[X] Wrong: "Adding one character to a string inside a loop takes the same time no matter how long the string is."
[OK] Correct: Strings are immutable, so each addition makes a new string by copying all characters, which takes more time as the string grows.
Understanding how string operations grow helps you write code that runs faster and avoids surprises in real projects.
What if we used a StringBuilder instead of adding characters directly? How would the time complexity change?
Practice
String in Kotlin is immutable?Solution
Step 1: Understand immutability concept
Immutability means the object cannot be changed after creation.Step 2: Apply to Kotlin String
Kotlin Strings cannot be modified once created; any change creates a new String.Final Answer:
Once created, the text inside a String cannot be changed. -> Option CQuick Check:
String immutability = cannot change text [OK]
- Thinking you can change characters inside the same String
- Confusing immutability with variable reassignment
- Believing Strings hold only numbers
str1 and str2 in Kotlin?Solution
Step 1: Recall Kotlin String concatenation syntax
Kotlin uses the + operator to join two Strings.Step 2: Check each option
Onlystr1 + str2is valid Kotlin syntax for concatenation.Final Answer:
str1 + str2 -> Option BQuick Check:
Use + to join Strings [OK]
- Using methods like append or join which don't exist on Kotlin String
- Using & which is not a Kotlin operator for Strings
- Trying to modify Strings directly
val text = "Hello" val newText = text + " World" println(text)
Solution
Step 1: Understand String immutability and concatenation
The original Stringtextremains unchanged after concatenation.Step 2: Analyze the print statement
Onlytextis printed, which is still "Hello".Final Answer:
Hello -> Option AQuick Check:
Original String unchanged = Hello [OK]
- Assuming original String changes after + operation
- Confusing newText with text in print
- Ignoring immutability of Strings
var greeting = "Hi" greeting[0] = 'B' println(greeting)
Solution
Step 1: Check String mutability rules
Kotlin Strings are immutable; you cannot assign to an index.Step 2: Analyze the code line causing error
Linegreeting[0] = 'B'tries to change a character, which is invalid.Final Answer:
You cannot change characters in a String by index. -> Option DQuick Check:
Strings immutable = no index assignment [OK]
- Thinking var allows character change inside String
- Confusing char literals with strings
- Believing println can't print Strings
val words = listOf("cat", "dog", "bird")
val excitedWords = ???Which Kotlin code correctly does this considering String immutability?Solution
Step 1: Understand immutability and list transformations
Strings cannot be changed, so create new Strings with + "!".Step 2: Use map to transform each word into a new String
mapreturns a new list with transformed elements without modifying original.Final Answer:
val excitedWords = words.map { it + "!" } -> Option AQuick Check:
Use map + + operator for new list [OK]
- Trying to modify list elements directly with apply or forEach
- Using replace on list instead of Strings
- Assuming original list changes
Ready to prove it?
Pass the test and this pattern moves unknown
