3912. Valid Elements in an Array
Description
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.
Β
Example 1:
Input: nums = [1,2,4,2,3,2]
Output: [1,2,4,3,2]
Explanation:
nums[0]andnums[5]are always valid.nums[1]andnums[2]are strictly greater than every element to their left.nums[4]is strictly greater than every element to its right.- Thus, the answer is
[1, 2, 4, 3, 2].
Example 2:
Input: nums = [5,5,5,5]
Output: [5,5]
Explanation:
- The first and last elements are always valid.
- No other elements are strictly greater than all elements to their left or to their right.
- Thus, the answer is
[5, 5].
Example 3:
Input: nums = [1]
Output: [1]
Explanation:
Since there is only one element, it is always valid. Thus, the answer is [1].
Β
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solutions
Solution 1: Preprocessing the Array
We can preprocess the array to compute the maximum value to the right of each element and store it in an array \(\textit{right}\).
Then, we traverse the array from left to right, using a variable \(\textit{left}\) to keep track of the maximum value to the left of the current element. For each element, if it satisfies any of the following conditions, we add it to the answer:
- It is strictly greater than \(\textit{left}\).
- It is the last element of the array.
- It is strictly greater than \(\textit{right}[i + 1]\).
During the traversal, we continuously update the value of \(\textit{left}\).
After the traversal, we return the answer.
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |