0
0
C++programming~5 mins

Relational operators in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Relational operators
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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
How Execution Grows With Input

Each time we call the function, it does a fixed number of comparisons regardless of the numbers' size.

Input Size (n)Approx. Operations
10Up to 2 comparisons
100Up to 2 comparisons
1000Up to 2 comparisons

Pattern observation: The number of operations stays the same no matter how big the input numbers are.

Final Time Complexity

Time Complexity: O(1)

This means the time to compare two values does not grow with input size; it stays constant.

Common Mistake

[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.

Interview Connect

Understanding that relational operators run in constant time helps you reason about bigger algorithms where comparisons happen many times.

Self-Check

"What if we compared two arrays element by element instead of two single values? How would the time complexity change?"