I am preparing for interviews where my code would be judged based on optimizations, OOP concepts, code readability as well as my knowledge of JAVA and design patterns.
What comments will you give in code review for the below code?
This is my code for Kth Largest element in an Array. The logic is to create a K size max heap, and then add the smallest K elements to the heap. Total array size can be equal to INT_MAX and k can be as small as 2
import java.util.Comparator;
import java.util.PriorityQueue;
public class CustomArray {
class DecreasingComparator implements Comparator<Long> {
@Override
public int compare(Long firstNumber , Long secondNumber) {
return (int) (secondNumber - firstNumber);
}
}
public long findKthLargestElement(long[] input, int k) {
if(k < 1 || k > input.length) {
throw new IllegalArgumentException("Invalid k, should be between 1 and arra length");
}
PriorityQueue<Long> heap = new PriorityQueue<>(k, new DecreasingComparator());
for(int i=0; i<k;i++) {
heap.add(input[i]);
}
for(int i=k; i<input.length;i++) {
if(heap.peek() > input[i]) {
heap.poll();
heap.add(input[i]);
}
}
return heap.poll();
}
}