Opening the reading…
Opening the reading…
PREFIX SUM › PREFIX SUM
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →For an index i to be good, the k values ending at i - 1 must never increase as you move right, and the k values starting at i + 1 must never decrease as you move right. The value at i itself does not participate in either condition, so the two checks are deliberately separated around it.
For every position, record how long the current non-increasing run has continued from the left. Do the same from the right for non-decreasing runs. Then index i is good exactly when the run ending at i - 1 has length at least k and the run starting at i + 1 has length at least k. Each condition becomes a constant-time lookup instead of a scan.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The left and right passes each compare neighboring elements once, and the candidate scan examines each index at most once. The work is therefore a constant number of visits per array position, with no candidate rescanning a window. |
| Space | O(n) extra | The left and right run arrays each use O(n) working memory. The returned answer is required output and is excluded from this bound. This remains O(n) in the worst input shape because the summaries store one value for every position. |
#include <vector>
using namespace std;
class Solution {
public:
vector<int> goodIndices(vector<int>& nums, int k) {
int n = nums.size();
vector<int> left(n, 1), right(n, 1);
for (int i = 1; i < n; ++i) {
if (nums[i] <= nums[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; --i) {
if (nums[i] <= nums[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
vector<int> ans;
for (int i = k; i < n - k; ++i) {
if (left[i - 1] >= k && right[i + 1] >= k) {
ans.push_back(i);
}
}
return ans;
}
};The two neighboring comparisons use <= in both passes, but their meanings differ because the scan directions differ. In the left-to-right pass, nums[i] <= nums[i - 1] means the sequence has not increased. In the right-to-left pass, nums[i] <= nums[i + 1] means the sequence will not decrease when read from left to right.