Code Logo

Filter In-Place with retain()

Published at25 Jul 2026
Rust Data Structures Medium 0 views
Like0

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

Example 1
Input
[]
Output
[]
Explanation

Empty stays empty

Example 2
Input
[-2,-1,0,1,2]
Output
[-2,0,2]
Explanation

Evens including negatives and zero

Example 3
Input
[2,4,6]
Output
[2,4,6]
Explanation

All evens, nothing removed

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

Retain only even numbers

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

No evens, all removed

Algorithm Flow

Recommendation Algorithm Flow for Filter In-Place with retain()

Solution Approach

Keep only elements in a Vec that satisfy a condition using retain(). This method removes all elements for which the closure returns false, modifying the Vec in place. Elements are removed efficiently by shifting remaining elements forward.

fn solution(v: &mut Vec<i32>) { v.retain(|&x| x > 0); }

retain() is the inverse of filter(): retain keeps matching elements, filter creates a new Vec with matches. It runs in O(n) time and preserves the order of retained elements.

Time O(n), Space O(1).

Best Answers

rust - Approach 1
fn solution(nums: &mut Vec<i32>) -> Vec<i32> {
    nums.retain(|&x| x % 2 == 0);
    nums.clone()
}