Vector creation in Rust - Time & Space Complexity
When we create a vector in Rust, it is important to know how the time it takes grows as the vector gets bigger.
We want to understand how the work changes when we add more items to the vector.
Analyze the time complexity of the following code snippet.
let mut v = Vec::new();
for i in 0..n {
v.push(i);
}
This code creates an empty vector and adds numbers from 0 up to n-1 one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an element to the vector with
push. - How many times: Exactly n times, once for each number from 0 to n-1.
Each new item is added one after another, so the total work grows as we add more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 push operations |
| 100 | About 100 push operations |
| 1000 | About 1000 push operations |
Pattern observation: The work grows directly with the number of items added.
Time Complexity: O(n)
This means the time to create the vector grows in a straight line as we add more items.
[X] Wrong: "Adding each item takes a lot longer because the vector must copy all items every time."
[OK] Correct: Rust vectors allocate extra space ahead of time, so most push operations are quick and do not copy all items every time.
Understanding how vector creation time grows helps you explain how data structures work behind the scenes, a useful skill in many programming tasks.
What if we used Vec::with_capacity(n) before the loop? How would the time complexity change?
Practice
Solution
Step 1: Understand how to create an empty vector
In Rust, an empty vector is created usingVec::new()with the type specified if needed.Step 2: Check each option
let v: Vec<i32> = Vec::new(); usesVec::new()with typei32, which is correct. let v = vec!(); usesvec!()which is invalid syntax. let v = Vector::new(); usesVector::new()which is not a Rust type. let v = vec![0]; creates a vector with one element 0, not empty.Final Answer:
let v: Vec<i32> = Vec::new(); -> Option AQuick Check:
Empty vector = Vec::new() [OK]
- Using vec!() with empty parentheses
- Using Vector instead of Vec
- Creating vector with one element instead of empty
Solution
Step 1: Recall vector creation with values
Rust uses the macrovec![...]with square brackets and exclamation mark to create vectors with initial values.Step 2: Evaluate each option
let v = vec![1, 2, 3]; uses correct syntaxvec![1, 2, 3]. let v = Vec[1, 2, 3]; uses square brackets without exclamation mark, invalid. let v = vec(1, 2, 3); uses parentheses, invalid. let v = vec{1, 2, 3}; uses curly braces, invalid.Final Answer:
let v = vec![1, 2, 3]; -> Option DQuick Check:
Vector with values = vec![...] [OK]
- Missing exclamation mark after vec
- Using parentheses or curly braces instead of brackets
- Using Vec[...] which is invalid syntax
let mut v = Vec::new();
v.push(10);
v.push(20);
println!("{:?}", v);Solution
Step 1: Understand vector push operations
The vector starts empty.push(10)adds 10 at the end, thenpush(20)adds 20 after 10.Step 2: Check the printed output
Theprintln!("{:?}", v)prints the vector in debug format showing all elements in order: [10, 20].Final Answer:
[10, 20] -> Option AQuick Check:
Push adds elements in order [OK]
- Assuming push adds at the front
- Printing vector without debug format
- Confusing order of elements
let v = Vec::new(); v.push(5);
Solution
Step 1: Check vector mutability
The vectorvis declared withoutmut, so it is immutable by default.Step 2: Understand push method requirements
Thepushmethod requires the vector to be mutable to add elements. Trying to push to an immutable vector causes a compile error.Final Answer:
Cannot push to an immutable vector -> Option CQuick Check:
push needs mutable vector [OK]
- Forgetting mut keyword
- Thinking Vec::new() returns non-vector
- Assuming push works on immutable vectors
Solution
Step 1: Convert &str slices to String vector
The array of &str slices needs to be converted to a vector ofStringusingiter(),map()withto_string(), thencollect().Step 2: Add a new String element
After creating a mutable vector, usepushwith"d".to_string()to add a new string.Step 3: Check other options
let v = vec!["a", "b", "c"]; v.push("d"); tries to push to an immutable vector of &str slices, invalid. let mut v = Vec::new(); v.push(["a", "b", "c"]); v.push("d"); tries to push an array inside vector, invalid. let mut v = vec![String::from("a"), String::from("b"), String::from("c")]; v.push('d'); pushes a char instead of String, invalid.Final Answer:
let mut v: Vec<String> = ["a", "b", "c"].iter().map(|&s| s.to_string()).collect(); v.push("d".to_string()); -> Option BQuick Check:
Convert slices to String vector, then push String [OK]
- Trying to push to immutable vector
- Pushing wrong types (char instead of String)
- Not converting &str slices to String
Ready to prove it?
Pass the test and this pattern moves unknown
