0
0
Cprogramming~5 mins

Nested conditional statements - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional statements
O(1)
Understanding Time Complexity

We want to see how the time to run nested conditional statements changes as input changes.

Are these conditions making the program slower when inputs grow?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int checkValue(int x) {
    if (x > 0) {
        if (x % 2 == 0) {
            return 1;
        } else {
            return 2;
        }
    } else {
        return 3;
    }
}
    

This code checks a number and returns different results based on nested conditions.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single check of conditions (if-else statements)
  • How many times: Exactly once per function call
How Execution Grows With Input

The program only checks conditions once, no matter the input size.

Input Size (n)Approx. Operations
102-3 checks
1002-3 checks
10002-3 checks

Pattern observation: The number of operations stays the same regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "Nested ifs always make the program slower as input grows."

[OK] Correct: Nested conditions run only once per input, so they do not slow down with bigger inputs.

Interview Connect

Understanding how conditions affect time helps you explain your code clearly and shows you know what really costs time in programs.

Self-Check

"What if we added a loop around these nested conditions? How would the time complexity change?"