0
0
Cprogramming~5 mins

Defensive programming practices - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Defensive programming practices
O(n)
Understanding Time Complexity

When writing defensive code, we add checks and safeguards to avoid errors.

We want to see how these extra checks affect how long the program takes to run.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int safe_sum(int *arr, int size) {
    if (arr == NULL || size <= 0) {
        return 0; // Defensive check
    }
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}
    

This code sums numbers in an array but first checks if the input is valid to avoid errors.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that adds each array element.
  • How many times: It runs once for each element in the array (size times).
How Execution Grows With Input

The time to run grows directly with the number of elements because each one is added once.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows steadily as the input grows, no surprises from the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items to add.

Common Mistake

[X] Wrong: "Adding defensive checks makes the program much slower for big inputs."

[OK] Correct: The checks run only once and do not grow with input size, so they don't change the main growth pattern.

Interview Connect

Understanding how safety checks affect performance shows you care about writing reliable code that still runs efficiently.

Self-Check

"What if we added a nested loop inside the for-loop to check each element against all others? How would the time complexity change?"