LeetCode 2200: Find All K-Distant Indices in an Array Solution

Master LeetCode problem 2200 (Find All K-Distant Indices in an Array), a easy 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.

2200. Find All K-Distant Indices in an Array

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and keep track of the indices where we find the key value. For each index where we find the key value, we then check the neighboring indices within a distance of k and add them to the result if they also contain the key value.

Time Complexity

The time complexity of this approach is O(n*k) where n is the number of elements in the array and k is the given distance.

Space Complexity

The space complexity is O(1) as we are not using any extra space other than the result list.

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
        List<Integer> result = new ArrayList<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == key) {
                result.add(i);
                for (int j = 1; j <= k; j++) {
                    if (i - j >= 0 && nums[i - j] == key) {
                        result.add(i - j);
                    }
                    if (i + j < nums.length && nums[i + j] == key) {
                        result.add(i + j);
                    }
                }
            }
        }
        
        result.sort(null);
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2200 (Find All K-Distant Indices in an Array)?

This page provides optimized solutions for LeetCode problem 2200 (Find All K-Distant Indices in an Array) 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 2200 (Find All K-Distant Indices in an Array)?

The time complexity for LeetCode 2200 (Find All K-Distant Indices in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2200 on DevExCode?

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

Back to LeetCode Solutions