String Traversal and Character Access in DSA Go - Time & Space Complexity
We want to know how the time to check each character in a string grows as the string gets longer.
How does the work change when the string size changes?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
func printChars(s string) {
for i := 0; i < len(s); i++ {
fmt.Printf("%c ", s[i])
}
fmt.Println()
}
This code goes through each character in the string and prints it one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Exactly once for each character in the string.
As the string gets longer, the number of steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The work grows in a straight line with the string length.
Time Complexity: O(n)
This means the time to run the code grows directly with the number of characters in the string.
[X] Wrong: "Accessing each character is constant time, so the whole loop is constant time too."
[OK] Correct: Even though each character access is quick, the loop runs once per character, so total time grows with string length.
Understanding how string traversal time grows helps you explain and predict performance in many coding tasks involving text.
"What if we only checked every second character instead of every character? How would the time complexity change?"
Practice
len(s) return when s is a string in Go?Solution
Step 1: Understand what
In Go,lendoes on strings in Golen(s)returns the number of bytes, not characters, because strings are byte slices.Step 2: Differentiate bytes and characters
Characters (runes) can be multiple bytes, solencounts bytes, not runes.Final Answer:
The number of bytes in the string -> Option DQuick Check:
len(s) = bytes count [OK]
- Thinking len counts characters (runes)
- Confusing bytes with characters
- Assuming len returns a character
s in Go?Solution
Step 1: Recall Go string indexing
Go strings can be indexed like byte slices, starting at 0, so the third character is at index 2.Step 2: Check syntax options
Onlys[2]is valid Go syntax for accessing a byte at index 2.Final Answer:
s[2] -> Option BQuick Check:
Indexing starts at 0, third char = s[2] [OK]
- Using 1-based indexing like s[3]
- Using methods like charAt or get which don't exist in Go
- Confusing bytes with runes
package main
import "fmt"
func main() {
s := "GoLang"
fmt.Println(string(s[1]))
}Solution
Step 1: Identify the character at index 1
String "GoLang" indexed at 1 is byte for 'o'.Step 2: Convert byte to string for printing
Usingstring(s[1])converts byte 'o' to string "o".Final Answer:
o -> Option AQuick Check:
s[1] = 'o' printed as string [OK]
- Printing byte as number instead of string
- Confusing index 1 with 0
- Expecting syntax error
package main
import "fmt"
func main() {
s := "hello"
for i := 0; i <= len(s); i++ {
fmt.Printf("%c", s[i])
}
}Solution
Step 1: Analyze loop range
The loop runs from i=0 to i=len(s) inclusive, but valid indices are 0 to len(s)-1.Step 2: Identify error cause
At i=len(s), s[i] causes index out of range runtime error.Final Answer:
Loop condition causes index out of range error -> Option AQuick Check:
Index must be less than len(s) [OK]
- Using <= instead of < in loop condition
- Ignoring runtime index out of range error
- Misunderstanding string indexing
s containing Unicode characters, which Go code snippet correctly prints each character (rune) on a new line?Solution
Step 1: Understand Unicode handling in Go strings
Go strings are byte slices; indexing gives bytes, not runes. To get runes, userangeloop.Step 2: Check each option
for _, r := range s { fmt.Println(string(r)) } usesfor _, r := range swhich iterates runes correctly and prints each rune as string.Final Answer:
for _, r := range s { fmt.Println(string(r)) } -> Option CQuick Check:
Use range to iterate runes in string [OK]
- Using byte indexing for Unicode characters
- Looping with <= len(s)
- Printing bytes directly without conversion
Ready to prove it?
Pass the test and this pattern moves unknown
