Skip to content

2420. Find All Good Indices 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<int> goodIndices(vector<int>& nums, int k) {
    const int n = nums.size();
    vector<int> ans;
    vector<int> dec(n, 1);  // dec[i] := continuous decreasing before i
    vector<int> inc(n, 1);  // inc[i] := continuous increasing after i

    for (int i = 1; i < n; ++i)
      if (nums[i - 1] >= nums[i])
        dec[i] = dec[i - 1] + 1;

    for (int i = n - 2; i >= 0; --i)
      if (nums[i] <= nums[i + 1])
        inc[i] = inc[i + 1] + 1;

    for (int i = k; i < n - k; ++i)
      if (dec[i - 1] >= k && inc[i + 1] >= k)
        ans.push_back(i);

    return ans;
  }
};
 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
class Solution {
  public List<Integer> goodIndices(int[] nums, int k) {
    final int n = nums.length;
    List<Integer> ans = new ArrayList<>();
    int[] dec = new int[n]; // dec[i] := continuous decreasing before i
    int[] inc = new int[n]; // inc[i] := continuous increasing before i

    Arrays.fill(dec, 1);
    Arrays.fill(inc, 1);

    for (int i = 1; i < n; ++i)
      if (nums[i - 1] >= nums[i])
        dec[i] = dec[i - 1] + 1;

    for (int i = n - 2; i >= 0; --i)
      if (nums[i] <= nums[i + 1])
        inc[i] = inc[i + 1] + 1;

    for (int i = k; i < n - k; ++i)
      if (dec[i - 1] >= k && inc[i + 1] >= k)
        ans.add(i);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def goodIndices(self, nums: List[int], k: int) -> List[int]:
    n = len(nums)
    dec = [1] * n  # dec[i] := continuous decreasing before i
    inc = [1] * n  # inc[i] := continuous increasing after i

    for i in range(1, n):
      if nums[i - 1] >= nums[i]:
        dec[i] = dec[i - 1] + 1

    for i in range(n - 2, -1, -1):
      if nums[i] <= nums[i + 1]:
        inc[i] = inc[i + 1] + 1

    return [i for i in range(k, n - k)
            if dec[i - 1] >= k and inc[i + 1] >= k]

    return ans