Filter In-Place with retain()
Write a Rust function that uses Vec::retain() to filter elements in place, keeping only the even numbers. The retain() method takes a closure predicate and removes all elements for which the closure returns false, modifying the original vector without allocating a new one.
Vec::retain() is an efficient in-place filtering operation. Unlike filter().collect() which creates a new allocation, retain() shifts elements within the existing buffer, only shrinking the vector. This makes it more memory-efficient when you want to filter without keeping the original data. The closure receives a mutable reference to each element.
The retain() method is part of Rust's standard library and is available on Vec, LinkedList, and VecDeque. It operates in O(n) time where n is the vector length, as it scans through elements and shifts surviving ones toward the front. Unlike drain-filter which can also remove elements, retain() is simpler and doesn't return an iterator of removed items.
Time complexity is O(n) where n is the vector length. The method visits each element once and shifts surviving elements. Space complexity is O(1) as no new allocation is created. The original vector's capacity is preserved.
Edge cases include empty vectors (no elements to filter), all elements passing the predicate (no removals), all elements failing (all removed, vector becomes empty), and negative numbers where the modulo operator must correctly identify even values.
Example Input & Output
Empty stays empty
Evens including negatives and zero
All evens, nothing removed
Retain only even numbers
No evens, all removed
Algorithm Flow

Solution Approach
Best Answers
fn solution(nums: &mut Vec<i32>) -> Vec<i32> {
nums.retain(|&x| x % 2 == 0);
nums.clone()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
