Code Logo

Remove Range with drain()

Published at25 Jul 2026
Rust Data Structures Medium 0 views
Like0

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

Example 1
Input
[1,2,3,4],0,4
Output
[1,2,3,4]
Explanation

Drain entire vector

Example 2
Input
[1,2,3],2,3
Output
[3]
Explanation

Drain last element

Example 3
Input
[1,2,3,4,5],1,4
Output
[2,3,4]
Explanation

Drain indices 1..4 from [1,2,3,4,5]

Example 4
Input
[10,20,30],0,2
Output
[10,20]
Explanation

Drain first two elements

Example 5
Input
[5,6,7],1,2
Output
[6]
Explanation

Drain middle element

Algorithm Flow

Recommendation Algorithm Flow for Remove Range with drain()
Recommendation Algorithm Flow for Remove Range with drain()

Solution Approach

fn solution(nums: &mut Vec<i32>, start: usize, end: usize) -> Vec<i32> {
    nums.drain(start..end).collect()
}

Best Answers

rust - Approach 1
fn solution(nums: &mut Vec<i32>, start: usize, end: usize) -> Vec<i32> {
    nums.drain(start..end).collect()
}