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: k=2 Window CheckInput: nums = [2,1,1,1,3,4,1], k = 221113410123456Before: [2,1] ↓After: [1,3] ↑Before: [1,1] ↓After: [3,4] ↑Condition: k elements before ↓ non-increasingCondition: k elements after ↑ non-decreasingOutput: [2,3]
Understanding the Visualization
1
Input Array
Array with elements and target k value
2
Check Conditions
Verify k elements before non-increasing, k after non-decreasing
3
Good Indices
Return all indices satisfying both conditions
Key Takeaway
🎯 Key Insight: Pre-compute sequence properties to avoid redundant validation checks
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