0
0
Rustprogramming~5 mins

Match guards in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Match guards
O(n)
Understanding Time Complexity

We want to see how using match guards affects the time it takes for a program to run.

Specifically, how the number of checks grows as the input gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn count_even_greater_than_five(numbers: &[i32]) -> usize {
    let mut count = 0;
    for &num in numbers {
        match num {
            n if n % 2 == 0 && n > 5 => count += 1,
            _ => (),
        }
    }
    count
}
    

This code counts how many numbers in a list are even and greater than five using a match with a guard.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list once.
  • How many times: Exactly once for each number in the input list.
How Execution Grows With Input

Each number is checked once with the match guard condition.

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

Pattern observation: The number of checks grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Match guards make the code slower by adding extra loops or checks for each condition."

[OK] Correct: The match guard only adds a simple condition check inside the existing loop, so it does not add extra loops or multiply the work.

Interview Connect

Understanding how match guards affect performance helps you write clear and efficient Rust code, a skill that shows you think about both correctness and speed.

Self-Check

"What if we added a nested loop inside the match guard to check something else? How would the time complexity change?"