0
0
Rustprogramming~5 mins

Basic match usage in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Basic match usage
O(1)
Understanding Time Complexity

Let's see how the time it takes to run a simple match statement changes as the input changes.

We want to know how many steps the program does when it checks different values.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn describe_number(num: i32) -> &'static str {
    match num {
        1 => "one",
        2 => "two",
        3 => "three",
        _ => "other",
    }
}
    

This code checks a number and returns a word for 1, 2, or 3, or "other" if it is something else.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The match statement compares the input number to fixed cases.
  • How many times: It checks each case once until it finds a match or reaches the default.
How Execution Grows With Input

Each time the function runs, it checks a few fixed cases no matter what number you give it.

Input Size (n)Approx. Operations
1Checks up to 1 case
2Checks up to 2 cases
10Checks up to 3 cases then default

Pattern observation: The number of checks stays small and does not grow with input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run does not grow as the input number gets bigger.

Common Mistake

[X] Wrong: "The match will take longer if the number is bigger."

[OK] Correct: The match only checks a few fixed cases, so it does not depend on how big the number is.

Interview Connect

Understanding that simple match statements run in constant time helps you explain how your code handles choices quickly and clearly.

Self-Check

"What if we added 100 more cases to the match? How would the time complexity change?"