You are given a 0-indexed integer array nums
and two integers key
and k
. A k-distant index
is an index i
of nums
for which there exists an 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: [1,2,3,4,5,6]
Explanation: Here, nums[3] and nums[5] are the indices with value 9, and they affect the adjacent indices within a range of 1. Therefore, the resulting indices are [1, 2, 3, 4, 5, 6].
nums
?nums
or the values of key
and k
?nums
match key
?k
is much larger than the length of nums
?nums
to find all indices j
where nums[j] == key
.j
, compute the range of indices influenced by this key index as [max(0, j - k), min(len(nums) - 1, j + k)]
.Here’s the C++ code that implements the strategy:
#include <vector>
#include <set>
#include <algorithm>
std::vector<int> findKDistantIndices(std::vector<int>& nums, int key, int k) {
std::set<int> kDistantIndices;
// Find all indices containing the key
for (int j = 0; j < nums.size(); ++j) {
if (nums[j] == key) {
// Add k-distant indices for each key occurrence
for (int i = std::max(0, j - k); i <= std::min(int(nums.size()) - 1, j + k); ++i) {
kDistantIndices.insert(i);
}
}
}
// Convert set to sorted vector
return std::vector<int>(kDistantIndices.begin(), kDistantIndices.end());
}
n
is the length of nums
(single traversal to find key indices).n
is the size of the set (in the worst case, the set may store each element of the array).Overall, the algorithm is efficient given the constraints typically present in such problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?