Find All Good Indices Problem
#2420
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2420.
You are given a 0-indexed integer array nums of size n and a positive integer k.
We call an index i in the range k <= i < n - k good if the following conditions are satisfied:
- The
kelements that are just before the indexiare in non-increasing order. - The
kelements that are just after the indexiare in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2
Output: [2,3]
Explanation: There are two good indices in the array:
- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.
- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.
Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2
Output: []
Explanation: There are no good indices in this array.
Constraints:
n == nums.length3 <= n <= 10^51 <= nums[i] <= 10^61 <= k <= n / 2
Solution
Approach: Prefix and Suffix Runs
Let decr[i] be the length of the non-increasing run that ends right before index i (looking at nums[..i-1]), and incr[i] the length of the non-decreasing run starting right after i. Fill decr from the left and incr from the right.
An index i in [k, n - k) is good when decr[i] >= k and incr[i] >= k.
Complexity: O(n) time and O(n) extra space.
class Solution:
def goodIndices(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
decr = [1] * (n + 1)
incr = [1] * (n + 1)
for i in range(2, n - 1):
if nums[i - 1] <= nums[i - 2]:
decr[i] = decr[i - 1] + 1
for i in range(n - 3, -1, -1):
if nums[i + 1] <= nums[i + 2]:
incr[i] = incr[i + 1] + 1
return [i for i in range(k, n - k) if decr[i] >= k and incr[i] >= k]