LeetCode Courses 3912. Valid Elements in an Array
LeetCode

3912. Valid Elements in an Array

We iterate from a brute-force scan to a two-pass sweep that walks a running max from each end. The "two-pass running max" pattern handles any "greater than everything to one side" question in linear time.

1 chapter Beginner Written walk-through Updated 5 May 2026 Phil · @FirnoxGames
Free

Free for everyone. No account needed.

Start reading →

What you'll learn

1 3912. Valid Elements in an Array 📖 9 min read

We iterate from a brute-force scan to a two-pass sweep that walks a running max from each end. The "two-pass running max" pattern handles any "greater than everything to one side" question in linear time.

In this chapter
  1. Problem
  2. Brute force
  3. Partial optimisation
  4. Final solution

Problem

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.

Included with this course
📖Written version of every chapter