0
0
Cprogramming~5 mins

Reusability and maintenance - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reusability and maintenance
O(n)
Understanding Time Complexity

When we write reusable and maintainable code, we want to know how it affects how long the program takes to run.

We ask: does making code reusable change how the program grows with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int data[] = {1, 2, 3, 4, 5};
    printArray(data, 5);
    return 0;
}
    

This code uses a reusable function to print elements of an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside printArray that goes through each array element.
  • How many times: It runs once for each element in the array, so size times.
How Execution Grows With Input

As the array gets bigger, the loop runs more times, directly matching the size.

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

Pattern observation: The number of steps grows evenly as the input size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the input.

Common Mistake

[X] Wrong: "Making code reusable always makes it slower or more complex."

[OK] Correct: Reusable code often just wraps the same steps in a function, so the main work still grows the same way with input size.

Interview Connect

Understanding how reusable functions affect time helps you write clean code without worrying about hidden slowdowns.

Self-Check

"What if the reusable function called another function inside a nested loop? How would the time complexity change?"