Find All K-Distant Indices in an Array — LeetCode 2200 Python Solution

EasyArrayTwo Pointers
Problem
#2200
Reading time
2 min

The 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.

Example

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.

Python solution

Python
class Solution:
    def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
        ans = []
        n = len(nums)
        for i in range(n):
            if any(abs(i - j) <= k and nums[j] == key for j in range(n)):
                ans.append(i)
        return ans

Complexity

MeasureComplexity
TimeO(n^2), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2200. Find All K-Distant Indices in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2200. Find All K-Distant Indices in an Array?
LeetCode 2200. Find All K-Distant Indices in an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2200. Find All K-Distant Indices in an Array?
The Python solution on this page runs in O(n^2), where n is the length of the array nums.
What is the space complexity of LeetCode 2200. Find All K-Distant Indices in an Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2200. Find All K-Distant Indices in an Array cover?
LeetCode 2200. Find All K-Distant Indices in an Array is tagged Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview