2420. Find All Good Indices
Description
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 <= 1051 <= nums[i] <= 1061 <= k <= n / 2
Solutions
Solution 1: Recursion
Thinking
At \(n\le 10^5\), checking \(k\) neighbors on each side per index can reach \(O(nk)\). The two sides are independent, so precompute the non-increasing run ending at \(i-1\) and the one starting at \(i+1\).
Fill \(\textit{decr}\) left to right and \(\textit{incr}\) right to left, then accept \(i\in[k,n-k)\) when both runs are at least \(k\). Both sides are non-increasing, matching the two \(\le\) comparisons in the code.
We define two arrays decr and incr, which represent the longest non-increasing and non-decreasing subarray lengths from left to right and from right to left, respectively.
We traverse the array, updating the decr and incr arrays.
Then we sequentially traverse the index \(i\) (where \(k\le i \lt n - k\)), if \(decr[i] \geq k\) and \(incr[i] \geq k\), then \(i\) is a good index.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |