- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 55 lines of C++ from the credited upstream file valid-elements-in-an-array.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<int> findValidElements(vector<int>& nums) {8 vector<bool> right(size(nums));9 int mx = 0;10 for (int i = size(nums) - 1; i >= 0; --i) {11 right[i] = nums[i] > mx;12 mx = max(mx, nums[i]);13 }14 vector<int> result;15 bool left = false;16 mx = 0;17 for (int i = 0; i < size(nums); ++i) {18 left = nums[i] > mx;19 mx = max(mx, nums[i]);20 if (left || right[i]) {21 result.emplace_back(nums[i]);22 }23 }24 return result;25 }26};27 28293031class Solution2 {32public:33 vector<int> findValidElements(vector<int>& nums) {34 vector<bool> left(size(nums));35 int mx = 0;36 for (int i = 0; i < size(nums); ++i) {37 left[i] = nums[i] > mx;38 mx = max(mx, nums[i]);39 }40 vector<bool> right(size(nums));41 mx = 0;42 for (int i = size(nums) - 1; i >= 0; --i) {43 right[i] = nums[i] > mx;44 mx = max(mx, nums[i]);45 }46 vector<int> result;47 for (int i = 0; i < size(nums); ++i) {48 if (left[i] || right[i]) {49 result.emplace_back(nums[i]);50 }51 }52 return result;53 }54};55