Find All K-Distant Indices in an Array — LeetCode 2200 Python Solution
- Problem
- #2200
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the length of the array nums |
| Space | O(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.