0
0
Goprogramming~5 mins

If–else statement in Go - Time & Space Complexity

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

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

Does the program take longer if the input is bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func checkNumber(n int) string {
    if n > 0 {
        return "Positive"
    } else {
        return "Non-positive"
    }
}
    

This code checks if a number is positive or not and returns a message.

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-else statement runs once no matter what the input number is.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

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

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if-else does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "If-else takes longer when the number is bigger because it has to check more."

[OK] Correct: The if-else only checks once and does not loop or repeat, so input size does not affect it.

Interview Connect

Understanding that simple decisions like if-else run in constant time helps you explain how your code behaves clearly and confidently.

Self-Check

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