Relational operators in C++ - Time & Space Complexity
Relational operators compare values to decide true or false. We want to see how long these comparisons take as input changes.
How does the time to compare values grow when we use relational operators in code?
Analyze the time complexity of the following code snippet.
int compareValues(int a, int b) {
if (a < b) {
return -1;
} else if (a == b) {
return 0;
} else {
return 1;
}
}
This code compares two numbers and returns which one is smaller, or if they are equal.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Up to two relational comparisons (<, ==)
- How many times: Each comparison runs once per function call
Each time we call the function, it does a fixed number of comparisons regardless of the numbers' size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 2 comparisons |
| 100 | Up to 2 comparisons |
| 1000 | Up to 2 comparisons |
Pattern observation: The number of operations stays the same no matter how big the input numbers are.
Time Complexity: O(1)
This means the time to compare two values does not grow with input size; it stays constant.
[X] Wrong: "Comparing bigger numbers takes more time than smaller numbers."
[OK] Correct: Computers compare numbers by their bits in fixed steps, so size does not affect comparison time.
Understanding that relational operators run in constant time helps you reason about bigger algorithms where comparisons happen many times.
"What if we compared two arrays element by element instead of two single values? How would the time complexity change?"