Find the First Array Element Smaller Than Both of Its Neighbors
Capital OneSoftware Engineer · Online AssessmentLast updated
A coding problem that asks for the first element of an integer array whose left and right neighbors are both strictly larger than it, returning -1 when no element qualifies. It tests careful boundary handling, strict comparisons when neighbors are equal, and precise output rules.
Given an array of integers, find the first element, scanning from left to right, whose two adjacent neighbors are both strictly larger than it.
Function Signature
def first_dip(nums: list[int]) -> int:
Rules
- The element at index
ihas two adjacent neighbors only when0 < i < len(nums) - 1. The first and last elements never qualify. - The element at index
iqualifies whennums[i - 1] > nums[i]andnums[i + 1] > nums[i]. A neighbor equal to the element does not count as larger. - Return the value of the qualifying element with the smallest index.
- Return
-1if no element qualifies, including when the array has fewer than 3 elements.
Constraints
1 <= len(nums) <= 10^50 <= nums[i] <= 10^9, so the result-1can never be confused with an element.
Examples
Example 1
Input: nums = [5, 3, 4, 1, 2]
Output: 3
The element 3 at index 1 has neighbors 5 and 4, both larger. The element 1 at index 3 also qualifies, but it comes later.
Example 2
Input: nums = [2, 2, 7, 6, 9, 0]
Output: 6
Index 1 does not qualify because its left neighbor 2 is equal, not larger. Index 2 holds 7, which is larger than both of its neighbors. Index 3 holds 6, whose neighbors 7 and 9 are both larger.
Example 3
Input: nums = [1, 2, 2, 3]
Output: -1
Index 1 has the smaller neighbor 1, and index 2 has the equal neighbor 2, so no element qualifies.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.