Find All K-Distant Indices in an Array
Real-world version: Positions Near a Given ReadingThe statement here is our own: the same inputs, outputs and technique.
A row of readings is given, together with a value key that turns up somewhere in the row and a whole number k.
A position i is near when the row holds key at some position j with the gap between i and j no more than k.
Return every near position, in increasing order.
Examples
Example 1
- Input
- readings = [5, 1, 1, 1, 5], key = 5, k = 1
- Output
- [0, 1, 3, 4]
The value sits at each end of the row, so both ends and their single neighbours are near, while the middle position is two steps from either end.
Example 2
- Input
- readings = [4, 1, 1, 1, 1, 1, 1, 4], key = 4, k = 2
- Output
- [0, 1, 2, 5, 6, 7]
The value sits at each end again, and reaching two steps inwards from each covers the first three and the last three positions.
Example 3
- Input
- readings = [7, 7, 7], key = 7, k = 3
- Output
- [0, 1, 2]
Every position holds the value, so every position is near.
Constraints
- 1 <= readings.length <= 1000
- 1 <= readings[i] <= 1000
- key turns up somewhere in readings
- 1 <= k <= readings.length
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def find_k_distant_indices(readings: list[int], key: int, k: int) -> list[int]:public List<Integer> findKDistantIndices(int[] readings, int key, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's