## Interview Question

**Country:**United States

Disclaimer: For finding the 3 largest numbers, the other solution is fine, and the one I am giving will be overkill. However, for solving k largest numbers, you can use a min heap:

```
import java.util.Arrays;
class KLargestNumbers {
public static void makeMinHeap(int arr[]) {
int n = arr.length / 2;
for (int i = n; i >= 1; i--) {
fixHeap(arr, i);
}
}
public static void fixHeap(int[] arr, int i) {
// Executes a top-down heapify, starting from the index i
int left = 2*i;
int right = 2*i + 1;
int smallest = i;
if (left < arr.length && arr[left] < arr[smallest]) {
smallest = left;
}
if (right < arr.length && arr[right] < arr[smallest]) {
smallest = right;
}
if (smallest != i) {
int t = arr[smallest];
arr[smallest] = arr[i];
arr[i] = t;
fixHeap(arr, smallest);
}
}
public static void insertIntoHeap(int[] heap, int i) {
// If the number is larger than the smallest number in the heap
// Replace it with the root, and then heapify top-down
if (i > heap[1]) {
heap[1] = i;
fixHeap(heap, 1);
}
}
public static int[] kLargest(int[] arr, int k) {
int[] minHeap = new int[k + 1];
for (int i = 0; i < k; i++) {
minHeap[i + 1] = arr[i];
}
makeMinHeap(minHeap);
for (int i = k; i < arr.length; i++) {
insertIntoHeap(minHeap, arr[i]);
}
int[] kLargestNums = new int[k];
for (int i = 0; i < k; i++) {
kLargestNums[i] = minHeap[i + 1];
}
return kLargestNums;
}
public static void main(String[] args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++) {
arr[i] = Integer.parseInt(args[i]);
}
System.out.println(Arrays.toString(kLargest(arr, 3)));
}
}
```

```
java KLargestNumbers 8 0 2 3 1 11 0 -5 18 21 25
[18, 25, 21]
```

```
java KLargestNumbers 0 -10 -100 -25 -8 -11
[-10, -8, 0]
```

1) One can sort the array and then get the three largest from the end of the array. But this will be O(nlogn) solution depending on the sorting technique used.

2) Initiate first, second and third element with MIN_Value. Compare each element with the first ,second and third element as we move along the array.

Time Complexity : O(n) Space Complexity : O(1)

- akira November 04, 2017