String Reversal Approaches in DSA Go - Time & Space Complexity
We want to understand how the time needed to reverse a string changes as the string gets longer.
How does the work grow when the input string size increases?
Analyze the time complexity of the following code snippet.
package main
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
This code reverses a string by swapping characters from the start and end moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop swaps characters from both ends moving inward.
- How many times: It runs about half the length of the string (n/2 times).
As the string gets longer, the number of swaps grows roughly in direct proportion to its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 swaps |
| 100 | 50 swaps |
| 1000 | 500 swaps |
Pattern observation: Doubling the string length roughly doubles the number of swaps needed.
Time Complexity: O(n)
This means the time to reverse the string grows linearly with the string length.
[X] Wrong: "Reversing a string takes constant time because we just swap characters."
[OK] Correct: Each character must be visited and swapped, so the time grows with string length, not fixed.
Understanding how string reversal scales helps you reason about similar problems involving arrays or strings, a common skill interviewers look for.
"What if we used recursion to reverse the string? How would the time complexity change?"
Practice
strings.Reverse function do in Go if it existed? (Assume it reverses the string.)Solution
Step 1: Understand the function name and purpose
The function nameReversesuggests it changes the order of characters.Step 2: Interpret the expected behavior
Reversing a string means the last character becomes first, and so on.Final Answer:
It returns the input string with characters in reverse order. -> Option BQuick Check:
Reverse means flip order [OK]
- Confusing reverse with uppercase conversion
- Thinking reverse removes characters
- Assuming reverse splits words
s?Solution
Step 1: Analyze the loop direction
var reversed string for i := len(s)-1; i >= 0; i-- { reversed += string(s[i]) } loops from the last character to the first, building reversed string.Step 2: Check other options
for i := 0; i < len(s); i++ { reversed += string(s[i]) } loops forward, so no reversal. reversed := strings.ToUpper(s) changes case, reversed := strings.Split(s, " ") splits words.Final Answer:
Option A correctly reverses the string. -> Option AQuick Check:
Loop backward to reverse [OK]
- Looping forward instead of backward
- Using string functions that don't reverse
- Confusing splitting with reversing
func main() {
s := "hello"
reversed := ""
for i := len(s) - 1; i >= 0; i-- {
reversed += string(s[i])
}
fmt.Println(reversed)
}Solution
Step 1: Trace the loop from end to start
The loop starts at index 4 ('o') and goes to 0 ('h'), appending characters in reverse order.Step 2: Build the reversed string
Characters appended: 'o', 'l', 'l', 'e', 'h' forming "olleh".Final Answer:
olleh -> Option AQuick Check:
Reverse of "hello" is "olleh" [OK]
- Reading string forward instead of backward
- Printing original string by mistake
- Expecting error due to string indexing
s:
func reverse(s string) string {
var reversed string
for i := 0; i <= len(s); i++ {
reversed += string(s[len(s)-i])
}
return reversed
}Solution
Step 1: Check loop bounds
The loop runs from 0 to len(s) inclusive, but string indices go from 0 to len(s)-1.Step 2: Identify out-of-range index
Accessing s[len(s)-i] when i=0 is s[len(s)], which is out of range and causes runtime error.Final Answer:
The loop condition should be i < len(s), not <=. -> Option CQuick Check:
Index must be within 0 to len(s)-1 [OK]
- Using <= instead of < in loop condition
- Accessing index len(s) which is invalid
- Confusing string and byte slice types
"Go语言", which approach correctly reverses it preserving characters properly in Go?Solution
Step 1: Understand Unicode in Go strings
Go strings are byte sequences; Unicode characters may be multiple bytes.Step 2: Use rune slice to handle Unicode characters
Converting to []rune treats each Unicode character as one element, safe to reverse.Step 3: Reverse rune slice and convert back
Reversing []rune reverses characters correctly, then convert back to string.Final Answer:
Convert string to []rune, reverse runes, then back to string. -> Option DQuick Check:
Use runes for Unicode-safe reversal [OK]
- Reversing bytes breaks Unicode characters
- Using uppercase conversion instead of reversing
- Reversing words instead of characters
Ready to prove it?
Pass the test and this pattern moves unknown
