#2420
Find All Good Indices
MediumArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can optimize by precomputing the non-increasing and non-decreasing conditions for the elements before and after each index. This allows us to check the conditions in constant time for each index.
⚙️
Algorithm
4 steps- 1Step 1: Create two arrays, left and right, to store the lengths of non-increasing and non-decreasing sequences.
- 2Step 2: Fill the left array by iterating from left to right, counting how many elements are non-increasing.
- 3Step 3: Fill the right array by iterating from right to left, counting how many elements are non-decreasing.
- 4Step 4: Iterate through the indices from k to n-k-1 and check if left[i] >= k and right[i] >= k.
solution.py21 lines
1# Full working Python code
2
3def findGoodIndices(nums, k):
4 n = len(nums)
5 left = [0] * n
6 right = [0] * n
7 good_indices = []
8
9 for i in range(1, n):
10 if nums[i] <= nums[i - 1]:
11 left[i] = left[i - 1] + 1
12
13 for i in range(n - 2, -1, -1):
14 if nums[i] <= nums[i + 1]:
15 right[i] = right[i + 1] + 1
16
17 for i in range(k, n - k):
18 if left[i] >= k and right[i] >= k:
19 good_indices.append(i)
20
21 return good_indicesℹ
Complexity note: The time complexity is O(n) because we only make three passes through the array: one for the left array, one for the right array, and one to collect good indices.
- 1Precomputation can significantly reduce the time complexity.
- 2Understanding the problem constraints helps in designing efficient algorithms.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.