2200. Find All K-Distant Indices in an Array #1846
-
Topics: You are given a 0-indexed integer array Return a list of all k-distant indices sorted in increasing order. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find all k-distant indices in an array. A k-distant index Approach
Let's implement this solution in PHP: 2200. Find All K-Distant Indices in an Array <?php
/**
* @param Integer[] $nums
* @param Integer $key
* @param Integer $k
* @return Integer[]
*/
function findKDistantIndices($nums, $key, $k) {
$n = count($nums);
$diff = array_fill(0, $n + 1, 0);
for ($j = 0; $j < $n; $j++) {
if ($nums[$j] == $key) {
$start = max(0, $j - $k);
$end = min($n - 1, $j + $k);
$diff[$start] += 1;
$diff[$end + 1] -= 1;
}
}
$curr = 0;
$result = [];
for ($i = 0; $i < $n; $i++) {
$curr += $diff[$i];
if ($curr > 0) {
$result[] = $i;
}
}
return $result;
}
// Test cases
$nums1 = array(3, 4, 9, 1, 3, 9, 5);
$key1 = 9;
$k1 = 1;
print_r(findKDistantIndices($nums1, $key1, $k1));
// Output: [1, 2, 3, 4, 5, 6]
$nums2 = array(2, 2, 2, 2, 2);
$key2 = 2;
$k2 = 2;
print_r(findKDistantIndices($nums2, $key2, $k2));
// Output: [0, 1, 2, 3, 4]
?> Explanation:
This approach efficiently marks all k-distant indices using the line sweep technique, ensuring optimal performance with O(n) time and space complexity. |
Beta Was this translation helpful? Give feedback.
We need to find all k-distant indices in an array. A k-distant index
i
is defined as an index where there exists at least one indexj
such that the absolute difference betweeni
andj
is at mostk
and the value atj
is equal to the givenkey
.Approach
Problem Analysis: The task involves identifying all indices
i
in the array that are within a distancek
from any indexj
wherenums[j]
equalskey
. The solution requires efficiently marking all such indicesi
without duplicates and returning them in sorted order.Intuition: For each occurrence of
key
in the array, we can determine the range of indices[j - k, j + k]
that are k-distant. To efficiently mark these indices, we use a line swee…