0
0
Goprogramming~5 mins

Else–if ladder in Go - Time & Space Complexity

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

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

Specifically, how many checks happen when we run the code?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkNumber(n int) string {
    if n == 1 {
        return "One"
    } else if n == 2 {
        return "Two"
    } else if n == 3 {
        return "Three"
    } else {
        return "Other"
    }
}
    

This code checks a number against several conditions one by one until it finds a match or reaches the last else.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As the input number changes, the code checks conditions in order until it finds a match.

Input Value (n)Approx. Operations
11 check (first condition matches)
22 checks (first fails, second matches)
43 checks (all conditions fail, last else runs)

Pattern observation: The number of checks grows linearly with how far down the ladder the match is.

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: "Else-if ladder always runs in constant time because it just checks a few conditions."

[OK] Correct: The time depends on where the match is found; if it's near the end, many checks happen, so time grows with the number of conditions.

Interview Connect

Understanding how else-if ladders scale helps you explain decision-making code clearly and shows you can think about efficiency in simple condition checks.

Self-Check

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