0
0
Cprogramming~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 fast these comparisons run 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 compare(int a, int b) {
    if (a > b) {
        return 1;
    } else {
        return 0;
    }
}
    

This code compares two numbers and returns 1 if the first is greater, otherwise 0.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: One relational comparison (a > b)
  • How many times: Exactly once per function call
How Execution Grows With Input

Each time we call this function, it does one comparison no matter the numbers.

Input Size (n)Approx. Operations
1010 comparisons if called 10 times
100100 comparisons if called 100 times
10001000 comparisons if called 1000 times

Pattern observation: The number of operations grows directly with how many times the function is called, but each call is just one quick comparison.

Final Time Complexity

Time Complexity: O(1)

This means the comparison takes the same short time no matter what numbers we compare.

Common Mistake

[X] Wrong: "Comparing bigger numbers takes longer time."

[OK] Correct: Computers compare numbers in fixed steps regardless of size, so time stays constant.

Interview Connect

Understanding that simple comparisons run in constant time helps you reason about bigger programs where many comparisons happen.

Self-Check

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