Originally published byDev.to
Same problem as Q1 but with larger constraints (up to 10^5). The O(n) approach with suffix min and prefix max is required.
Approach
Precompute suffix minimums. Scan left to right with a running prefix maximum. Return the first index where prefix_max - suffix_min <= k.
Time: O(n) · Space: O(n)
Code
class Solution:
def firstStableIndex(self, nums: list[int], k: int) -> int:
n = len(nums)
if n == 0:
return -1
suff_min = [0] * n
suff_min[-1] = nums[-1]
for i in range(n - 2, -1, -1):
suff_min[i] = min(suff_min[i + 1], nums[i])
current_max = -float("inf")
for i in range(n):
current_max = max(current_max, nums[i])
if current_max - suff_min[i] <= k:
return i
return -1
Interactive Trace
Step through this solution on TraceLit — set breakpoints to see exactly when the instability score drops below k.
🇺🇸
More news from United StatesUnited States
NORTH AMERICA
Related News
UCP Variant Data: The #1 Reason Agent Checkouts Fail
7h ago
Amazon Employees Are 'Tokenmaxxing' Due To Pressure To Use AI Tools
21h ago
How Braze’s CTO is rethinking engineering for the agentic area
10h ago

Décryptage technique : Comment builder un téléchargeur de vidéos Reddit performant (DASH, HLS & WebAssembly)
17h ago
How AI Reduced Manual Driver Verification by 75% — Operations Case Study. Part 2
4h ago