Skip to content

Link to Question

EASY

2200. Find All K-Distant Indices

Given a 0-indexed integer array nums and two integers key and k, a k-distant index is an index i of nums such that there exists at least one index j such that |i - j| <= k and nums[j] == key.

Return a list of all k-distant indices sorted in increasing order.

Example

Input:

nums = [3,4,9,1,3,9,5], key = 9, k = 1
Output:
[2,3,4,5,6]
Explanation: Indices 2, 3, 4, 5, and 6 are k-distant indices.


Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000
  • 0 ≤ k ≤ nums.length
  • 0 ≤ key ≤ 1000

Solution: Brute Force

  • Time Complexity: O(n), where n is the length of nums.
  • Space Complexity: O(n), for the result array.
C++
class Solution {
public:
    vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
        int n = nums.size();
        vector<int> res;
        for (int i = 0; i < n; ++i) {
            for (int j = max(0, i - k); j <= min(n - 1, i + k); ++j) {
                if (nums[j] == key) {
                    res.push_back(i);
                    break;
                }
            }
        }
        return res;
    }
};