0
0
Goprogramming~5 mins

If statement in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If statement
O(1)
Understanding Time Complexity

We want to see how the time to run an if statement changes as the input changes.

Does the if statement take more time when inputs grow?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkNumber(n int) string {
    if n > 0 {
        return "Positive"
    } else if n == 0 {
        return "Zero"
    } else {
        return "Negative"
    }
}
    

This code checks if a number is positive, zero, or negative and returns a string.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else check.
  • How many times: Exactly once per function call.
How Execution Grows With Input

The if statement runs once no matter what the input number is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same even if the input number changes.

Final Time Complexity

Time Complexity: O(1)

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

Common Mistake

[X] Wrong: "If statements take longer when the number is bigger."

[OK] Correct: The if statement only checks conditions once, so size or value does not affect time.

Interview Connect

Understanding that simple decisions like if statements run in constant time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we added a loop around the if statement? How would the time complexity change?"