0
0
Cprogramming~5 mins

Character arrays - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Character arrays
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets longer, the number of print steps grows directly with the number of characters.

Input Size (n)Approx. Operations
1010 print steps
100100 print steps
10001000 print steps

Pattern observation: The work grows in a straight line with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to print all characters grows directly with how many characters there are.

Common Mistake

[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.

Interview Connect

Understanding how loops over character arrays scale helps you explain performance clearly in interviews.

Self-Check

"What if we added a nested loop inside the print loop that also runs n times? How would the time complexity change?"