0
0
C++programming~5 mins

Else–if ladder in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Else-if ladder
O(n)
Understanding Time Complexity

We want to understand how the time taken by an else-if ladder changes as the input changes.

Specifically, we ask: How many steps does the program take before it finds the right condition?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int checkNumber(int n) {
    if (n == 1) {
        return 10;
    } else if (n == 2) {
        return 20;
    } else if (n == 3) {
        return 30;
    } else {
        return 40;
    }
}
    

This code checks the value of n and returns a number based on which condition matches first.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking conditions one by one in the else-if ladder.
  • How many times: Up to the number of conditions until a match is found.
How Execution Grows With Input

As the input number changes, the program checks conditions from top to bottom until it finds a match.

Input Value (n)Approx. Operations (condition checks)
11 check
22 checks
33 checks
44 checks (all conditions checked)

Pattern observation: The number of checks grows linearly with the position of the matching condition.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of conditions checked before finding a match.

Common Mistake

[X] Wrong: "The else-if ladder always takes the same time regardless of input."

[OK] Correct: The program stops checking as soon as it finds a match, so time depends on where the match is.

Interview Connect

Understanding how condition checks add up helps you explain efficiency clearly and shows you can think about code beyond just making it work.

Self-Check

"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"