0
0
Javaprogramming~5 mins

Else–if ladder in Java - 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, how many checks happen before the program finds the right condition?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int number = 15;
if (number < 10) {
    System.out.println("Less than 10");
} else if (number < 20) {
    System.out.println("Between 10 and 19");
} else if (number < 30) {
    System.out.println("Between 20 and 29");
} else {
    System.out.println("30 or more");
}
    

This code checks a number against several conditions one by one until one matches.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Sequential condition checks in the else-if ladder.
  • How many times: Up to the number of conditions until one matches.
How Execution Grows With Input

As the input number changes, the program checks conditions one by one until it finds a match.

Input Size (number of conditions)Approx. Operations (checks)
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows linearly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of conditions checked.

Common Mistake

[X] Wrong: "The else-if ladder checks all conditions every time."

[OK] Correct: The program stops checking as soon as one condition is true, so it does not always check all conditions.

Interview Connect

Understanding how else-if ladders work helps you explain decision-making in code clearly and shows you can analyze simple control flows efficiently.

Self-Check

"What if we replaced the else-if ladder with separate if statements? How would the time complexity change?"