Remove Range with drain()
Write a Rust function that uses Vec::drain() to remove a range of elements (from start to end) from a vector and return them as a new vector. The drain() method creates an iterator that yields and removes elements over the specified range, preserving the remaining elements in the original vector.
Vec::drain() is unique to Rust's ownership model. Unlike other languages where removing elements requires separate index tracking, drain() returns an iterator that yields owned elements. The original vector is modified in place: elements before the range stay, elements after the range shift left. The drained elements are moved into the iterator, which can be collected into a new vector.
The drain() method takes a Range argument using the .. syntax. It panics if the range is out of bounds. The range is exclusive on the end bound (start..end). After draining, the vector's length decreases by the number of drained elements, but capacity is preserved. This makes drain() more efficient than repeated remove() calls.
Time complexity is O(n) where n is the vector length after the drained range, as elements after the range must be shifted. The drained elements are moved (memcpy for simple types). Space complexity is O(k) for the collected result where k is the number of drained elements.
Edge cases include draining from the beginning (0..n), draining the entire vector (0..len), draining a single element (i..i+1), and ensuring the function handles empty lists correctly (though drain with empty range is not expected).
Example Input & Output
Drain entire vector
Drain last element
Drain indices 1..4 from [1,2,3,4,5]
Drain first two elements
Drain middle element
Algorithm Flow

Solution Approach
Best Answers
fn solution(nums: &mut Vec<i32>, start: usize, end: usize) -> Vec<i32> {
nums.drain(start..end).collect()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
