Find All Good Indices - Problem

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 k elements that are just before the index i are in non-increasing order.
  • The k elements that are just after the index i are in non-decreasing order.

Return an array of all good indices sorted in increasing order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,1,1,3,4,1], k = 2
Output: [2,3]
💡 Note: For index 2: elements [2,1] before are non-increasing, elements [1,3] after are non-decreasing. For index 3: elements [1,1] before are non-increasing, elements [3,4] after are non-decreasing.
Example 2 — No Good Indices
$ Input: nums = [1,1,1,1], k = 2
Output: []
💡 Note: No valid indices exist since we need at least k elements before and after any potential good index, but array length is only 4.
Example 3 — Minimum Valid Case
$ Input: nums = [3,2,1,2,3], k = 1
Output: [1,2,3]
💡 Note: Index 1: [3] before non-increasing, [1] after non-decreasing. Index 2: [2] before non-increasing, [2] after non-decreasing. Index 3: [1] before non-increasing, [3] after non-decreasing.

Constraints

  • n == nums.length
  • 3 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ n / 2

Visualization

Tap to expand
Find All Good Indices INPUT nums array: 2 0 1 1 1 2 1 3 3 4 4 5 1 6 k = 2 Good Index Conditions: 1. k elements before: non-increasing 2. k elements after: non-decreasing 3. Valid range: k <= i < n-k Valid indices: [2, 3, 4] (where 2 <= i < 5) ALGORITHM STEPS 1 Precompute prefix array Count non-increasing from left 2 Precompute suffix array Count non-decreasing from right 3 Check each valid index prefix[i-1] >= k AND suffix[i+1] >= k 4 Collect good indices Add to result if both conditions met prefix[] (non-increasing count): 1 2 3 4 1 2 1 suffix[] (non-decreasing count): 1 2 3 4 3 2 1 Time: O(n) | Space: O(n) FINAL RESULT Checking Index 2: Before [0,1]: 2,1 non-incr? OK After [3,4]: 1,3 non-decr? OK Index 2 is GOOD Checking Index 3: Before [1,2]: 1,1 non-incr? OK After [4,5]: 3,4 non-decr? OK Index 3 is GOOD Checking Index 4: Before [2,3]: 1,1 non-incr? OK After [5,6]: 4,1 non-decr? NO Output: [2, 3] Key Insight: Use prefix and suffix arrays to precompute the length of non-increasing and non-decreasing subarrays ending/starting at each index. This allows O(1) lookup for each candidate index, reducing overall complexity from O(n*k) brute force to O(n) optimal solution. TutorialsPoint - Find All Good Indices | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen