KatInterview

Locate Local Minima Using Divide-and-Conquer

Heaps, Sorting & SearchModel answer
HardModel answerHeaps, Sorting & Searchbinary-searchdivide-and-conqueralgorithms

Last updated

Implement sublinear algorithms to identify a local minimum in a 1D array and a 2D grid by applying binary search to unimodal descent.

Overview

An element in an array or grid is called a local minimum if it is strictly smaller than every adjacent neighbor. All values in the input are guaranteed to be distinct, ensuring at least one local minimum always exists.

Your task is to write two functions:

  1. find_local_min_1d(arr: list[int]) -> int
    Return the index of any local minimum in a one-dimensional array. An element arr[i] qualifies as a local minimum when it is strictly less than arr[i-1] (if i > 0) and strictly less than arr[i+1] (if i < len(arr) - 1).
    Required runtime: O(log n)

  2. find_local_min_2d(matrix: list[list[int]]) -> tuple[int, int]
    Return the coordinates (row, col) of any local minimum in an n × m grid. An element matrix[r][c] is a local minimum when it is strictly smaller than all orthogonally adjacent cells (up, down, left, right) that exist within bounds.
    Required runtime: O(n log m) or O(n + m)

Function Signatures

def find_local_min_1d(arr: list[int]) -> int:
    pass

def find_local_min_2d(matrix: list[list[int]]) -> tuple[int, int]:
    pass

Input Specification

  • arr: A list of integers with length n ≥ 1
  • matrix: A 2D list of integers with dimensions n × m where n ≥ 1 and m ≥ 1
  • All elements within a single input are pairwise distinct
  • Return any valid local minimum when multiple exist

Constraints

  • 1 ≤ n, m ≤ 200,000
  • For the 2D case: 1 ≤ n × m ≤ 1,000,000
  • -10⁹ ≤ arr[i], matrix[r][c] ≤ 10⁹

Examples

Example 1: One-Dimensional Array

arr = [9, 7, 8, 5, 6, 4, 10]
# Valid outputs: 1 (value 7), 3 (value 5), or 5 (value 4)
# Returning index 1 is acceptable since 7 < 9 and 7 < 8

Example 2: Two-Dimensional Grid

matrix = [
    [10,  8, 11, 15],
    [ 9,  6,  7, 14],
    [12, 13,  5,  3],
    [16, 17,  4,  2]
]
# Valid outputs include (1, 1) where value 6 < 8, 9, 7, 13
# or (3, 3) where value 2 < 3, 4

Edge Cases to Consider

  • Single-element inputs (n = 1 or 1 × 1 grids) are trivially local minima
  • Monotonically increasing or decreasing sequences place the minimum at a boundary
  • Degenerate grids (1 × m or n × 1) should reduce naturally to the one-dimensional approach

Hints

Hint 1

For 1D: even though the array isn't sorted, you can still use binary search by observing the direction values are decreasing.

Hint 2

In 2D, apply binary search across one dimension (columns) while scanning the other (rows) to find a candidate in each iteration.

Hint 3

Maintain an invariant that guarantees a local minimum exists within your search window at every step.