Constants in Rust - Time & Space Complexity
When using constants in Rust, it's important to see how they affect the speed of a program.
We want to know how the program's running time changes as input grows when constants are involved.
Analyze the time complexity of the following code snippet.
const MAX: usize = 1000;
fn print_numbers() {
for i in 0..MAX {
println!("{}", i);
}
}
This code prints numbers from 0 up to a fixed constant MAX.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-loop running from 0 to MAX.
- How many times: Exactly MAX times, which is a fixed number.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1000 (constant) |
| 100 | 1000 (constant) |
| 1000 | 1000 (constant) |
Pattern observation: The number of operations stays the same no matter how input changes because MAX is fixed.
Time Complexity: O(1)
This means the running time does not grow with input size; it stays constant.
[X] Wrong: "Since there is a loop, the time must grow with input size."
[OK] Correct: The loop runs a fixed number of times set by a constant, so it does not depend on input size.
Understanding constants helps you explain why some parts of code run quickly no matter the input size, a useful skill in interviews.
"What if MAX was a variable input instead of a constant? How would the time complexity change?"