0
0
Rustprogramming~5 mins

Relational operators in Rust - 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 fast these comparisons run as input changes.

How does the time to compare values grow when we have more data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn count_greater_than(nums: &[i32], threshold: i32) -> usize {
    let mut count = 0;
    for &num in nums {
        if num > threshold {
            count += 1;
        }
    }
    count
}
    

This code counts how many numbers in a list are greater than a given threshold using relational operators.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Comparing each number to the threshold using the > operator inside a loop.
  • How many times: Once for every number in the input list.
How Execution Grows With Input

Each number is checked once, so the work grows evenly with the list size.

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

Pattern observation: The number of comparisons grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Relational operators take longer time as numbers get bigger."

[OK] Correct: The time to compare two numbers stays the same no matter how big the numbers are; only the number of comparisons matters.

Interview Connect

Understanding how simple comparisons scale helps you explain efficiency clearly and shows you know what really affects program speed.

Self-Check

"What if we checked pairs of numbers instead of single numbers? How would the time complexity change?"