LeetCode 2420: Find All Good Indices

LeetCode 2420 Solution Explanation

Explanation

To solve this problem, we iterate through the array and check each index satisfying the given conditions. We can use two pointers to traverse the k elements before and after the current index, ensuring they are in non-increasing and non-decreasing order respectively. If both conditions are met, we add the index to the result array.

  • Start by initializing an empty list to store the good indices.
  • Iterate through the array from index k to n-k.
  • For each index i, check the k elements before and after i to ensure they are in the required order.
  • If both conditions are satisfied, add i to the result list.
  • Finally, return the list of good indices sorted in increasing order.

The time complexity of this solution is O(n) as we iterate through the entire array once. The space complexity is O(1) as we are not using any additional space proportional to the input size.

LeetCode 2420 Solutions in Java, C++, Python

class Solution {
    public List<Integer> findGoodIndices(int[] nums, int k) {
        List<Integer> goodIndices = new ArrayList<>();
        for (int i = k; i < nums.length - k; i++) {
            if (checkGoodIndex(nums, i, k)) {
                goodIndices.add(i);
            }
        }
        return goodIndices;
    }
    
    private boolean checkGoodIndex(int[] nums, int idx, int k) {
        for (int j = 1; j <= k; j++) {
            if (nums[idx - j] < nums[idx - j + 1] || nums[idx + j] < nums[idx + j - 1]) {
                return false;
            }
        }
        return true;
    }
}

Interactive Code Editor for LeetCode 2420

Improve Your LeetCode 2420 Solution

Use the editor below to refine the provided solution for LeetCode 2420. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems