702982. Kth distance
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:
- Sort the array in ascending order.
- Initialize a variable
kto the value provided. - Iterate through the sorted array starting from the first element.
- For each element, calculate the difference between the current element and the given distance from another specified integer in the array.
- If the difference is less than or equal to 0, decrement
k. Ifkbecomes 0, return the current element as it's the k-th smallest element that meets the condition. - If the end of the array is reached and
kis 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;
}
Not available