Find All K-Distant Indices in an Array

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.

Example 1
Inputnums = [3,4,9,1,3,9,5], key = 9, k = 1
Output[1,2,3,4,5,6]
Indices 1 through 6 are within distance 1 of an index whose value is 9, while index 0 is not.
Example 2
Inputnums = [2,2,2,2,2], key = 2, k = 2
Output[0,1,2,3,4]
Every index is within distance 2 of some index whose value is 2, so every index is a k-distant index.

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • key is an integer from the array nums.
  • 1 <= k <= nums.length

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate