Skip to content

← leetcode

Find All K Distant Indices in an Array

· Easy

LeetCode problem 2200

We first initialize an ans array to keep track of all our answer indices.

Basically just iterate through the array nums, checking at each index to see if nums[i] == key:

  • if true, then we can reiterate through surrounding elements and add them to the ans array.
    • to avoid adding duplicate elements, we keep track of the maximum element added to the ans array and ensure that all future elements have a greater index
  • if false, then we just continue.

code

class Solution {
public:
    vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {
        vector<int> ans;
        int prev = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == key) {
                for (int j = max(prev, i-k); j < min((int)nums.size(), i+k+1); ++j) {
                    ans.push_back(j);
                }
                prev = i+k+1;
            }
        }
        return ans;
    }
};

complexity

  • Time: O(n) where n is the size of nums
  • Space: O(1)

time taken

  • 9 minutes and 52 seconds