0
0
Goprogramming~5 mins

Nested conditional statements in Go - Time & Space Complexity

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

When we use nested conditional statements, we want to know how they affect the time it takes for the program to run.

We ask: Does adding more conditions make the program slower as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

func checkNumber(n int) string {
    if n > 0 {
        if n % 2 == 0 {
            return "Positive even"
        } else {
            return "Positive odd"
        }
    } else if n < 0 {
        return "Negative"
    } else {
        return "Zero"
    }
}

This code checks if a number is positive, negative, or zero, and if positive, whether it is even or odd.

Identify Repeating Operations

Look for loops or repeated checks that happen many times.

  • Primary operation: Simple conditional checks (if-else).
  • How many times: Each check runs once per function call.
How Execution Grows With Input

The number of steps does not increase when the input number gets bigger.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

Pattern observation: The time stays the same no matter how big the number is.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter the input size.

Common Mistake

[X] Wrong: "More conditions always make the program slower as input grows."

[OK] Correct: These conditions run only once per input, so they do not slow down the program as input size increases.

Interview Connect

Understanding how nested conditions affect time helps you explain your code clearly and shows you know when performance matters.

Self-Check

"What if we added a loop inside the nested conditions that runs n times? How would the time complexity change?"