↓Skip to main content
  1. LeetCode/

LeetCode 3903: Smallest Stable Index I

·1 min· ·
LeetCode Easy Prefix-Sum 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-19

  • Submissions: Accepted (first try)

Approach
#

Each index scores max(nums[0..i]) - min(nums[i..n-1]); scan once from each side (Prefix Sum Template 2):

  • Build the suffix minimum right to left first.
  • Update the prefix maximum left to right, returning the first index scoring <= k.

Versions I and II differ only in the length limit (100 for I, 10^5 for II); I used the same O(n) code for both, though for I’s small range computing max and min directly at every position, O(n²), also passes. See LeetCode 3904 for the other one.

My Solution
#

class Solution:
    def firstStableIndex(self, nums: List[int], k: int) -> int:
        n = len(nums)
        suf_min = nums[:]
        for i in range(n - 2, -1, -1):
            suf_min[i] = min(suf_min[i + 1], nums[i])
        pre_max = -inf
        for i, x in enumerate(nums):
            pre_max = max(pre_max, x)
            if pre_max - suf_min[i] <= k:
                return i
        return -1

Complexity
#

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

Mistakes to Avoid
#

  • Both ranges include i itself.

Interview Explanation
#

The score is the maximum up to i minus the minimum from i. I build the suffix minimum right to left, then keep the prefix maximum left to right, and the first position with difference <= k is the answer. Time O(n).

Related

LeetCode 1413: Minimum Value to Get Positive Step by Step Sum
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1413 note: the start value plus every prefix sum must be at least 1, so it is max(1, 1 - minimum prefix sum)
LeetCode 1480: Running Sum of 1d Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1480 note: the definition of a prefix sum, adding each element to the previous running total
LeetCode 1732: Find the Highest Altitude
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1732 note: the altitudes are prefix sums of gain starting from 0; take the maximum
LeetCode 1991: Find the Middle Index in Array
·1 min
LeetCode Easy Array Prefix-Sum
LeetCode 1991 note: compute the total, maintain the left sum while scanning, and get the right sum as total - left - nums[i]
LeetCode 3904: Smallest Stable Index II
·1 min
LeetCode Medium Prefix-Sum Array
LeetCode 3904 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