702982. Kth distance

Easy

Kth distance3757

Summary

Given an array of integers, find the k-th smallest element that is at least a certain given distance from another specified integer in the array. This problem requires understanding arrays and data structures.

Detailed Explanation

The problem can be solved by first sorting the array. Then, we iterate through the array to find the k-th smallest element that meets the condition. The condition is that the difference between the current element and the given distance from another specified integer in the array should be less than or equal to 0.

Here's a step-by-step breakdown of the solution:

  1. Sort the array in ascending order.
  2. Initialize a variable k to the value provided.
  3. Iterate through the sorted array starting from the first element.
  4. For each element, calculate the difference between the current element and the given distance from another specified integer in the array.
  5. If the difference is less than or equal to 0, decrement k. If k becomes 0, return the current element as it's the k-th smallest element that meets the condition.
  6. If the end of the array is reached and k is still greater than 0, return -1 as there are not enough elements in the array to meet the condition.

Time complexity: O(n log n) due to sorting the array where n is the number of elements in the array. Space complexity: O(1) as we only use a constant amount of space to store variables.

Optimized Solutions

Java

java
public int kthDistance(int[] arr, int distance, int target, int k) {
    Arrays.sort(arr);
    for (int i = 0; i < arr.length; i++) {
        if (Math.abs(arr[i] - target) <= distance) {
            k--;
            if (k == 0) return arr[i];
        }
    }
    return -1;
}

Python

python
def kth_distance(arr, distance, target, k):
    arr.sort()
    for i in range(len(arr)):
        if abs(arr[i] - target) <= distance:
            k -= 1
            if k == 0:
                return arr[i]
    return -1

C++

cpp
int kthDistance(int* arr, int n, int distance, int target, int k) {
    sort(arr, arr+n);
    for (int i = 0; i < n; i++) {
        if (abs(arr[i] - target) <= distance) {
            k--;
            if (k == 0) return arr[i];
        }
    }
    return -1;
}

JavaScript

javascript
function kthDistance(arr, distance, target, k) {
    arr.sort((a, b) => a - b);
    for (let i = 0; i < arr.length; i++) {
        if (Math.abs(arr[i] - target) <= distance) {
            k--;
            if (k == 0) return arr[i];
        }
    }
    return -1;
}
View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.