Nested conditional statements in Go - Time & Space 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?
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.
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.
The number of steps does not increase when the input number gets bigger.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The time stays the same no matter how big the number is.
Time Complexity: O(1)
This means the program takes the same amount of time no matter the input size.
[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.
Understanding how nested conditions affect time helps you explain your code clearly and shows you know when performance matters.
"What if we added a loop inside the nested conditions that runs n times? How would the time complexity change?"