Character arrays - Time & Space Complexity
When working with character arrays, it is important to understand how the time to process them grows as their size increases.
We want to know how the number of steps changes when we read or manipulate these arrays.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void printChars(char arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%c", arr[i]);
}
printf("\n");
}
int main() {
char message[] = "hello";
printChars(message, 5);
return 0;
}
This code prints each character in a character array one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each character.
- How many times: It runs once for each character in the array, so n times.
As the array gets longer, the number of print steps grows directly with the number of characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The work grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to print all characters grows directly with how many characters there are.
[X] Wrong: "The loop runs a fixed number of times regardless of array size."
[OK] Correct: The loop depends on the array length, so more characters mean more steps.
Understanding how loops over character arrays scale helps you explain performance clearly in interviews.
"What if we added a nested loop inside the print loop that also runs n times? How would the time complexity change?"