Skip to main content
Back to problems
#3912
Easy Algorithms

Valid elements in an array

57.1% acceptance
May 13, 2026
28
1
You are given an integer array nums. An element nums[i] is considered valid if it satisfies at least one of the following conditions: It is strictly greater than every element to its left. It is strictly greater than every element to its right. The first and last elements are always valid. Return an array of all valid elements in the same order as they appear in nums.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_valid_elements(nums: Vec<i32>) -> Vec<i32> {
    let n = nums.len();
    if n == 0 { return vec![]; }
    let mut left_max = vec![i32::MIN; n];
    let mut right_max = vec![i32::MIN; n];
    for i in 1..n {
      left_max[i] = left_max[i - 1].max(nums[i - 1]);
    }
    for i in (0..n - 1).rev() {
      right_max[i] = right_max[i + 1].max(nums[i + 1]);
    }
    let mut ans = Vec::new();
    for i in 0..n {
      if i == 0 || i == n - 1 || nums[i] > left_max[i] || nums[i] > right_max[i] {
        ans.push(nums[i]);
      }
    }
    ans
  }
}