String handling using library functions - Time & Space Complexity
When using library functions for strings, it's important to know how the time to run grows as the string gets longer.
We want to see how the work changes when the input string size changes.
Analyze the time complexity of the following code snippet.
#include <string.h>
int main() {
char str1[] = "hello world";
char str2[20];
strcpy(str2, str1);
int len = strlen(str2);
return 0;
}
This code copies one string to another and then finds the length of the copied string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The functions
strcpyandstrlenboth scan the string character by character. - How many times: Each function goes through the string until it finds the end (the null character).
As the string gets longer, both copying and measuring length take more steps, roughly one step per character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (10 for copy + 10 for length) |
| 100 | About 200 steps |
| 1000 | About 2000 steps |
Pattern observation: The total work grows roughly twice as fast as the string length because two passes happen.
Time Complexity: O(n)
This means the time to run grows directly with the length of the string.
[X] Wrong: "Using library functions like strcpy or strlen is always constant time because they are built-in."
[OK] Correct: These functions actually look at each character until they find the end, so their time depends on the string length.
Understanding how string functions work helps you explain your code clearly and shows you know what happens behind the scenes.
"What if we used strcat to append one string to another? How would the time complexity change?"