cswork / libraryOpen practice workspace

Coding questions · Uber

Find First Local Minimum

This question evaluates array-processing and algorithmic reasoning skills, specifically the ability to identify local minima and handle index-based and boundary-case conditions.

Given an integer array nums, find the index of the first local minimum.

A local minimum is an element that is smaller than its immediate neighbors:

  • For an interior index i, nums[i] is a local minimum if nums[i] < nums[i - 1] and nums[i] < nums[i + 1].
  • For index 0, it is a local minimum if the array has length 1, or if nums[0] < nums[1].
  • For index n - 1, it is a local minimum if nums[n - 1] < nums[n - 2].

Return the smallest index that satisfies the local-minimum condition. If no local minimum exists, return -1.

Example:

Input: nums = [5, 3, 4, 2, 6]
Output: 1
Explanation: nums[1] = 3 and nums[3] = 2 are both local minima, but index 1 is the first one.

Find First Local Minimum

Constraints

  • 0 <= len(nums) <= 100000
  • -1000000000 <= nums[i] <= 1000000000

Hints

  1. You only need to compare each element with its immediate neighbors, not the whole array.
  2. Handle the boundary indices 0 and n - 1 separately, then scan from left to right to find the first valid position.