Adding elements to vectors in Rust - Time & Space Complexity
When we add elements to a vector in Rust, it is important to know how the time it takes changes as the vector grows.
We want to understand how the cost of adding elements grows when the vector gets bigger.
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.
- Primary operation: Adding an element to the vector using
push. - How many times: Exactly n times, once for each number from 0 to n-1.
Each element is added one after another. Most adds are quick, but sometimes the vector needs to grow its storage, which takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 simple adds, with a few extra steps for resizing |
| 100 | About 100 adds, with a few resizing steps spread out |
| 1000 | About 1000 adds, resizing happens a few times but not every add |
Pattern observation: Most adds are quick, but occasionally the vector grows bigger, which costs more time. Overall, the time grows roughly in a straight line with n.
Time Complexity: O(n)
This means adding n elements takes time roughly proportional to n, growing steadily as more elements are added.
[X] Wrong: "Each push always takes the same small amount of time."
[OK] Correct: Sometimes the vector needs to resize its storage, which takes extra time. But these resizing steps happen rarely enough that the average time per push stays low.
Understanding how adding elements to a vector scales helps you reason about performance in many programs. It shows you how data structures behave as they grow, a useful skill for writing efficient code.
"What if we used a linked list instead of a vector? How would the time complexity of adding elements change?"
Practice
push method do when used on a Rust vector?Solution
Step 1: Understand the purpose of
Thepushpushmethod is used to add elements to a vector in Rust.Step 2: Identify what
It adds a new element to the end of the vector, increasing its size by one.pushdoes specificallyFinal Answer:
Adds a new element to the end of the vector -> Option BQuick Check:
pushadds element [OK]
- Confusing push with pop (which removes elements)
- Thinking push creates a new vector
- Assuming push sorts the vector
Solution
Step 1: Check vector mutability
To add elements, the vector must be mutable, solet mut vis required.Step 2: Use correct method to add element
The method to add an element ispush, notadd.Final Answer:
let mut v = Vec::new(); v.push(10); -> Option DQuick Check:
Mutable vector + push method [OK]
- Forgetting to make the vector mutable
- Using a non-existent method like add
- Trying to push on an immutable vector
let mut v = vec![1, 2];
v.push(3);
println!("{:?}", v);Solution
Step 1: Understand initial vector content
The vector starts with elements [1, 2].Step 2: Apply the push method
Thepush(3)adds 3 at the end, so vector becomes [1, 2, 3].Final Answer:
[1, 2, 3] -> Option CQuick Check:
push adds element at end [OK]
- Expecting push to add at the start
- Thinking push replaces elements
- Assuming code causes error
let v = Vec::new(); v.push(5);
Solution
Step 1: Check vector mutability
The vector is declared as immutable withlet v, so it cannot be changed.Step 2: Understand push method requirements
Thepushmethod requires the vector to be mutable to add elements.Final Answer:
Vector is not mutable, so push cannot be called -> Option AQuick Check:
push needs mutable vector [OK]
- Assuming push works on immutable vectors
- Thinking Vec::new() is invalid
- Ignoring mut keyword necessity
v. Which code correctly adds all these elements efficiently?Solution
Step 1: Understand adding multiple elements
Usingpushadds one element at a time, so multiple calls are needed for multiple elements.Step 2: Use the efficient method for multiple elements
Theextendmethod adds all elements from an iterable at once, which is more efficient.Final Answer:
v.extend([4, 5, 6]); -> Option AQuick Check:
Use extend for multiple elements [OK]
- Using push with a whole array (causes error)
- Using non-existent add method
- Calling push multiple times instead of extend
Ready to prove it?
Pass the test and this pattern moves unknown
