LeetCode 2420: Find All Good Indices Solution

Master LeetCode problem 2420 (Find All Good Indices), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2420. Find All Good Indices

Problem 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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2420 (Find All Good Indices)?

This page provides optimized solutions for LeetCode problem 2420 (Find All Good Indices) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2420 (Find All Good Indices)?

The time complexity for LeetCode 2420 (Find All Good Indices) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2420 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2420 in Java, C++, or Python.

Back to LeetCode Solutions