LeetCode in Kotlin

2200. Find All K-Distant Indices in an Array

Easy

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:

Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1

Output: [1,2,3,4,5,6]

Explanation: Here, nums[2] == key and nums[5] == key.

Thus, we return [1,2,3,4,5,6] which is sorted in increasing order.

Example 2:

Input: nums = [2,2,2,2,2], key = 2, k = 2

Output: [0,1,2,3,4]

Explanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index.

Hence, we return [0,1,2,3,4].

Constraints:

Solution

class Solution {
    fun findKDistantIndices(nums: IntArray, key: Int, k: Int): List<Int> {
        val ans: MutableList<Int> = ArrayList()
        var start = 0
        val n = nums.size
        for (i in 0 until n) {
            if (nums[i] == key) {
                start = Math.max(i - k, start)
                val end = Math.min(i + k, n - 1)
                while (start <= end) {
                    ans.add(start++)
                }
            }
        }
        return ans
    }
}