Basic match usage in Rust - Time & Space 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.
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 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.
Each time the function runs, it checks a few fixed cases no matter what number you give it.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | Checks up to 1 case |
| 2 | Checks up to 2 cases |
| 10 | Checks up to 3 cases then default |
Pattern observation: The number of checks stays small and does not grow with input size.
Time Complexity: O(1)
This means the time to run does not grow as the input number gets bigger.
[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.
Understanding that simple match statements run in constant time helps you explain how your code handles choices quickly and clearly.
"What if we added 100 more cases to the match? How would the time complexity change?"