Complexity and collection choice
Quick answer
Complexity describes how resource use grows with input size. Choose collections by their access pattern, not simply by habit.
Match operation to structure
A vector supports constant-time indexed access; removing its first element shifts later elements, which is linear time. A deque supports efficient operations at both ends. HashMap lookup is expected constant time under suitable hashing, not a universal worst-case guarantee. Big O describes an asymptotic upper bound; it is not an exact stopwatch measurement.
fn main() { let mut checks = 0; for x in [2, 4, 6, 8] { checks += 1; if x == 9 { break; } } println!("{checks}");}Expected stdout (not executed):
4A missing value requires scanning the entire input in this algorithm.
use std::collections::VecDeque;fn main() { let mut queue = VecDeque::from(["first", "second"]); queue.push_back("third"); println!("{:?}", queue.pop_front());}Expected stdout (not executed):
Some("first")A deque fits first-in-first-out processing.
Common mistake
Do not infer complexity from the timing of one tiny run.
Try it yourself
Compare the operation count of a linear search for the first and last item.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Complexity and collection choice — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A workload repeatedly removes the oldest queued element. Which collection avoids shifting every remaining element?
Complexity and collection choice — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut checks = 0; for x in [2, 4, 6, 8] { checks += 1; if x == 9 { break; } } println!("{checks}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Complexity and collection choice — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::collections::VecDeque; fn main() { let mut queue = VecDeque::from(["first", "second"]); queue.push_back("third"); println!("{:?}", queue.pop_front()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.