How Strings Work Differently Across Languages in DSA C - Complexity Walkthrough
When working with strings, how fast operations run depends on how strings are handled inside the language.
We want to see how string operations grow as the string gets longer.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
#include <string.h>
void print_chars(const char *str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
printf("%c ", str[i]);
}
printf("\n");
}
int main() {
print_chars("hello world");
return 0;
}
This code prints each character of a string one by one using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the string.
- How many times: Exactly once for each character in the string (length n).
As the string gets longer, the number of steps grows directly with its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character prints |
| 100 | About 100 character prints |
| 1000 | About 1000 character prints |
Pattern observation: The work grows in a straight line as the string length increases.
Time Complexity: O(n)
This means the time to print characters grows directly with the string length.
[X] Wrong: "Accessing any character in a string is always O(1) no matter the language."
[OK] Correct: In C, strings are arrays so access is O(1), but in some languages like Python or JavaScript, strings may be immutable or encoded differently, making some operations slower.
Understanding how strings work under the hood helps you explain your code choices clearly and shows you know how performance changes with input size.
"What if the string was stored as a linked list of characters instead of an array? How would the time complexity of accessing characters change?"
