If statement in Java - Time & Space Complexity
We want to see how the time it takes to run an if statement changes as the input changes.
Does the if statement make the program slower when the input grows?
Analyze the time complexity of the following code snippet.
int checkNumber(int n) {
if (n > 0) {
return 1;
} else {
return -1;
}
}
This code checks if a number is positive or not and returns a value accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if condition check.
- How many times: Exactly once per function call.
Whether the input is small or large, the if statement runs just once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the if statement takes the same amount of time no matter the input size.
[X] Wrong: "If statements take longer when the input number is bigger."
[OK] Correct: The if condition is checked only once, so input size does not affect its speed.
Understanding that simple decisions like if statements run in constant time helps you explain how your code behaves as inputs grow.
"What if we added a loop inside the if statement that runs n times? How would the time complexity change?"