Valid Elements in an Array Problem
Description
LeetCode Problem 3912.
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] and nums[5] are always valid.
- nums[1] and nums[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
Solution
Approach: Prefix and Suffix Maximum
An element is valid when it beats everything on its left or everything on its right, so we need the maximum on each side.
First build an array right, where right[i] is the maximum of nums[i..n-1]. Then scan from left to right while keeping left, the maximum of the elements before the current one (start it at 0, which is below every value). Keep nums[i] when it is strictly greater than left, when it is the last element, or when it is strictly greater than right[i + 1]. After each step update left.
Complexity: time O(n), space O(n), where n is the length of nums.
class Solution:
def findValidElements(self, nums: List[int]) -> List[int]:
n = len(nums)
right = [nums[-1]] * n
for i in range(n - 2, -1, -1):
right[i] = max(right[i + 1], nums[i])
left = 0
ans = []
for i, x in enumerate(nums):
if x > left or i == n - 1 or x > right[i + 1]:
ans.append(x)
left = max(left, x)
return ans