↓Skip to main content
  1. LeetCode/

LeetCode 3912: Valid Elements in an Array

·2 mins· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-04-26

  • Submissions: Accepted (first try)

Approach
#

“Strictly greater than everything on the left” means “strictly greater than the left maximum” (Array Template 3). Scan left to right marking elements above the prefix maximum, and right to left marking those above the suffix maximum; keep an element if either holds. The first and last elements have nothing to compare against on their side, so they get marked naturally.

My Solution
#

class Solution:
    def findValidElements(self, nums: List[int]) -> List[int]:
        n = len(nums)
        valid = [False] * n
        best = float("-inf")
        for i in range(n):
            if nums[i] > best:
                valid[i] = True
            best = max(best, nums[i])
        best = float("-inf")
        for i in range(n - 1, -1, -1):
            if nums[i] > best:
                valid[i] = True
            best = max(best, nums[i])
        return [x for x, ok in zip(nums, valid) if ok]

I originally put valid indices in a set and sorted them at the end; a boolean array avoids the sort.

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • It is strictly greater; equal to the maximum does not count.
  • Output in original order, without listing an element twice.

Interview Explanation
#

Greater than everything on the left equals greater than the prefix maximum, so I scan once each way marking valid elements and output them in original order. Time O(n).

Related

LeetCode 3903: Smallest Stable Index I
·1 min
LeetCode Easy Prefix-Sum Array
LeetCode 3903 note: the first index where the prefix maximum minus the suffix minimum is <= k; build the suffix minimum right to left first
LeetCode 3898: Find the Degree of Each Vertex
·1 min
LeetCode Easy Graph Matrix Array
LeetCode 3898 note: the number of ones in row i of the adjacency matrix is vertex i’s degree
LeetCode 3838: Weighted Word Mapping
·1 min
LeetCode Easy Array String Simulation
LeetCode 3838 note: sum each word’s letter weights mod 26 and map backward: 0 -> z, i.e. chr(ord(‘z’) - r)
LeetCode 3379: Transformed Array
·1 min
LeetCode Easy Array Simulation
LeetCode 3379 note: moving nums[i] steps right or left is nums[(i + nums[i]) % n]; Python’s % returns a non-negative result for negatives too
LeetCode 2540: Minimum Common Value
·2 mins
LeetCode Easy Two-Pointers Array
LeetCode 2540 note: one pointer per sorted array, advance the smaller side, and the first match is the answer
LeetCode 2570: Merge Two 2D Arrays by Summing Values
·2 mins
LeetCode Easy Two-Pointers Array
LeetCode 2570 note: merge two id-sorted arrays with two pointers, adding values when ids match