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 an element in the middle of the array?
Consider the Rust code below that inserts the value 99 into the middle of a vector. What will be the printed vector after insertion?
DSA Rust
fn main() {
let mut v = vec![10, 20, 30, 40];
let mid = v.len() / 2;
v.insert(mid, 99);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Remember that insert shifts elements to the right starting at the given index.
✗ Incorrect
The middle index is 2 (4/2). Inserting 99 at index 2 shifts elements at and after index 2 to the right.
❓ Predict Output
intermediateWhat is the output after inserting at the middle of an odd-length array?
Given the Rust code below, what will be the vector printed after inserting 77 in the middle?
DSA Rust
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let mid = v.len() / 2;
v.insert(mid, 77);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Integer division truncates. The middle index is floor of length/2.
✗ Incorrect
Length is 5, so middle index is 2. Insert 77 at index 2 shifts elements from index 2 right.
🔧 Debug
advancedWhat error does this Rust code produce when inserting at middle index?
Analyze the Rust code below. What error will it produce when run?
DSA Rust
fn main() {
let mut v = vec![5, 10, 15];
let mid = v.len() / 2;
v.insert(mid + 5, 20);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Check if the insert index is valid for the vector length.
✗ Incorrect
The insert index is 1 + 5 = 6, which is beyond vector length 3, causing panic at runtime.
🧠 Conceptual
advancedHow does inserting at the middle index affect the array elements?
When inserting an element at the middle index of an array or vector, what happens to the elements at and after that index?
Attempts:
2 left
💡 Hint
Think about how arrays maintain order when inserting.
✗ Incorrect
Insertion shifts elements at and after the insertion index right by one to keep all elements.
🚀 Application
expertAfter multiple middle insertions, what is the final vector?
Starting with an empty vector, the following insertions happen in order:
1. Insert 10 at middle
2. Insert 20 at middle
3. Insert 30 at middle
What is the final vector printed?
DSA Rust
fn main() {
let mut v = Vec::new();
let mid1 = v.len() / 2;
v.insert(mid1, 10);
let mid2 = v.len() / 2;
v.insert(mid2, 20);
let mid3 = v.len() / 2;
v.insert(mid3, 30);
println!("{:?}", v);
}Attempts:
2 left
💡 Hint
Calculate the middle index before each insertion carefully.
✗ Incorrect
Insertions happen at indices 0, then 0, then 1 shifting elements accordingly, resulting in [20, 30, 10].
