How Strings Work Differently Across Languages in DSA Go - Complexity Walkthrough
Strings are handled differently in programming languages, affecting how fast operations run.
We want to see how these differences change the time it takes to work with strings.
Analyze the time complexity of the following Go code that concatenates strings.
package main
import "fmt"
func main() {
s := ""
for i := 0; i < 5; i++ {
s += "a"
}
fmt.Println(s)
}
This code adds the letter 'a' to a string five times using the += operator.
Look at what repeats inside the loop.
- Primary operation: Adding one character to the string each time.
- How many times: 5 times (once per loop iteration).
Each time we add a character, the whole string is copied to a new space because strings are immutable in Go.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 + 2 + ... + 10 = 55 copies |
| 100 | 1 + 2 + ... + 100 = 5050 copies |
| 1000 | 1 + 2 + ... + 1000 = 500500 copies |
Pattern observation: The work grows much faster than the number of characters added because each addition copies the whole string again.
Time Complexity: O(n²)
This means if you add n characters one by one, the total work grows roughly like n times n, because each addition copies the whole string.
[X] Wrong: "Adding characters one by one to a string is always fast and takes O(n) time."
[OK] Correct: In Go, strings are immutable, so each addition creates a new string by copying all characters, making it slower than expected.
Understanding how strings behave in different languages helps you write efficient code and explain your choices clearly in interviews.
"What if we used a string builder or buffer instead of += for concatenation? How would the time complexity change?"
Practice
var s = "hello"Solution
Step 1: Understand Go string representation
Go strings are immutable sequences of bytes, typically UTF-8 encoded.Step 2: Compare with other languages
Unlike some languages that use arrays of Unicode code points, Go uses bytes internally.Final Answer:
A sequence of bytes representing UTF-8 encoded characters -> Option AQuick Check:
Go strings = UTF-8 bytes [OK]
- Thinking Go strings store runes directly
- Assuming null-terminated strings like C
- Confusing with linked list or array types
s := "hello"Solution
Step 1: Recall Go built-in function for length
Go uses the built-in function len() to get the length of strings and slices.Step 2: Check other options
Methods like s.length() or s.len do not exist in Go; length(s) is not valid syntax.Final Answer:
len(s) -> Option CQuick Check:
Use len() for string length in Go [OK]
- Using method calls like s.length() from other languages
- Trying to access length as a property
- Using undefined functions like length()
package main
import "fmt"
func main() {
s := "Go😊"
fmt.Println(len(s))
}Solution
Step 1: Analyze string content and encoding
The string "Go😊" has 'G' and 'o' as 1 byte each, and the emoji '😊' is a 4-byte UTF-8 character.Step 2: Calculate total byte length
Total bytes = 1 (G) + 1 (o) + 4 (😊) = 6 bytes.Step 3: Check len() output
len(s) returns the number of bytes, so output is 6.Final Answer:
6 -> Option BQuick Check:
len() counts bytes, not characters [OK]
- Assuming len() returns number of characters
- Ignoring multi-byte UTF-8 characters
- Confusing bytes with runes
package main
import "fmt"
func main() {
s := "Go"
for i := 0; i < len(s); i++ {
fmt.Println(s[i])
}
}Solution
Step 1: Understand s[i] in Go strings
Accessing s[i] returns the byte at index i, not a character or string.Step 2: Check output of fmt.Println(s[i])
It prints the numeric byte value (ASCII code), not the character itself.Final Answer:
It prints byte values, not characters -> Option AQuick Check:
s[i] = byte, prints number [OK]
- Expecting s[i] to print characters directly
- Ignoring byte vs rune difference
- Assuming syntax error where none exists
Choose the correct code snippet.
Solution
Step 1: Understand iteration over strings in Go
Using 'for _, r := range s' iterates over runes (Unicode code points), not bytes.Step 2: Check printing each character
Converting rune 'r' to string prints the actual character correctly.Step 3: Analyze other options
for i := 0; i < len(s); i++ { fmt.Println(string(s[i])) } prints bytes as strings, which may break multi-byte chars; C and D print bytes, not runes.Final Answer:
for _, r := range s { fmt.Println(string(r)) } -> Option DQuick Check:
Use range to get runes for correct Unicode iteration [OK]
- Iterating by byte index instead of runes
- Printing bytes as characters causing errors
- Confusing index and rune variables
Ready to prove it?
Pass the test and this pattern moves unknown
