Problem
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 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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Set
To solve this problem:
- Identify all indices
j
wherenums[j] == key
. - For each such index
j
, add all indicesi
in the range[j - k, j + k]
to a set to avoid duplicates. - Convert the set to a sorted list before returning it.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- We iterate through the entire array
nums
exactly once to identify the indices wherenums[j] == key
⇨ O(n) time - For each index
j
wherenums[j] == key
, we add indices in the range[j - k, j + k]
to a set. - In the worst case, there could be (n) such key indices.
- For each key index
j
, adding indices to the set could takeO(k)
, but this is bounded by the length of the subarray size, implying an upper limit proportional to (n) because (j - k) to (j + k) is at most 2k elements, and k can be up to (n). - Thus, adding elements to the set takes (O(n \times k)) but seen as (O(n)) since k is a constant compared to the linear scan.
- Sorting a list of size
n
takes (O(n \log n)).
- We iterate through the entire array
- 🧺 Space complexity:
O(n)