0
0
Javaprogramming~5 mins

Relational operators in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Relational operators
O(n)
Understanding Time Complexity

Relational operators compare values to decide true or false. We want to see how the time to do these comparisons changes as input grows.

How does the number of comparisons affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int count = 0;
for (int i = 0; i < n; i++) {
    if (i < 10) {
        count++;
    }
}
    

This code counts how many numbers from 0 to n-1 are less than 10 using a relational operator.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop runs from 0 to n-1, checking if each number is less than 10.
  • How many times: The relational check happens once per loop iteration, so n times.
How Execution Grows With Input

Each time n grows, the loop runs more times, so the number of comparisons grows too.

Input Size (n)Approx. Operations
1010 comparisons
100100 comparisons
10001000 comparisons

Pattern observation: The number of comparisons grows directly with n. Double n, double the comparisons.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Since the relational check is simple, it takes constant time no matter what."

[OK] Correct: While one check is quick, the total time depends on how many times it runs. More input means more checks, so total time grows with n.

Interview Connect

Understanding how simple comparisons add up helps you explain how loops affect performance. This skill shows you can think about code efficiency clearly.

Self-Check

"What if we replaced the loop with two nested loops both running n times? How would the time complexity change?"