[LeetCode] Valid Elements in an Array

3912. Valid Elements in an Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> findValidElements(vector<int>& nums) {
vector<bool> ok(nums.size());
for(int i = 0, ma = 0; i < nums.size(); i++) {
if(nums[i] > ma) ok[i] = true;
ma = max(ma, nums[i]);
}
for(int i = nums.size() - 1, ma = 0; i >= 0; i--) {
if(nums[i] > ma) ok[i] = true;
ma = max(ma, nums[i]);
}
vector<int> res;
for(int i = 0; i < nums.size(); i++) if(ok[i]) res.push_back(nums[i]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/valid-elements-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.