2 / 2
This is one of the most asked question from array in interviews. Find the "Kth" maximum and minimum element of an array in Java. This question is asked to check the logical skill and java knowledge of candidate. you can follow below steps to solve this problem:
- Sort the array in ascending order.
- The "Kth" minimum element will be at index
K-1
. - The "Kth" maximum element will be at index
array.length - K
.
Here's an example code snippet that demonstrates this approach:
javaimport java.util.Arrays;
public class KthMinMaxElement {
public static void main(String[] args) {
int[] array = {9, 5, 2, 7, 1, 8, 6, 3, 4};
// Sort the array in ascending order
Arrays.sort(array);
int k = 3;
// The value of k
// Find the Kth minimum element
int kthMin = array[k - 1];
System.out.println("Kth minimum element: " + kthMin);
// Find the Kth maximum element
int kthMax = array[array.length - k];
System.out.println("Kth maximum element: " + kthMax);
}
}
In this example, the array is {9, 5, 2, 7, 1, 8, 6, 3, 4}
. We want to find the 3rd minimum and maximum elements. The sorted array is {1, 2, 3, 4, 5, 6, 7, 8, 9}
, so the 3rd minimum element is 3, and the 3rd maximum element is 7.
You can modify the code according to your specific requirements by providing a different array and value for k
.