Challenge - 5 Problems
Array Insertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after inserting elements at the end of a Rust vector?
Consider the following Rust code that inserts elements at the end of a vector. What will be printed?
DSA Rust
fn main() {
let mut v = vec![1, 2, 3];
v.push(4);
v.push(5);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Remember that push adds elements to the end of the vector.
✗ Incorrect
The push method appends elements to the end of the vector, so after pushing 4 and 5, the vector becomes [1, 2, 3, 4, 5].
❓ Predict Output
intermediateWhat happens if you push an element to an empty vector?
What will be the output of this Rust code?
DSA Rust
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(10);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
An empty vector can have elements added with push.
✗ Incorrect
The vector starts empty. After pushing 10, it contains one element: [10].
❓ Predict Output
advancedWhat is the output after multiple insertions and a pop operation?
Analyze the following Rust code and determine the printed vector.
DSA Rust
fn main() {
let mut v = vec![5, 6];
v.push(7);
v.push(8);
v.pop();
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
pop removes the last element added.
✗ Incorrect
After pushing 7 and 8, vector is [5, 6, 7, 8]. pop removes 8, so vector becomes [5, 6, 7].
🔧 Debug
advancedWhy does this Rust code fail to compile when inserting at the end?
Identify the error in this Rust code and what error message it produces.
DSA Rust
fn main() {
let v = vec![1, 2, 3];
v.push(4);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Check if the vector is mutable before pushing.
✗ Incorrect
The vector `v` is declared immutable with `let`. The push method requires a mutable vector, so the compiler errors on borrowing immutable `v` as mutable.
🧠 Conceptual
expertWhat is the time complexity of inserting an element at the end of a Rust vector?
Consider a Rust vector with n elements. What is the average time complexity of the push operation that inserts an element at the end?
Attempts:
2 left
💡 Hint
Think about how vectors resize internally.
✗ Incorrect
Rust vectors allocate extra space. Most push operations are O(1), but occasionally resizing takes O(n). Averaged over many pushes, the time is O(1) amortized.
