Kth Largest Element

medium Arrays

Problem

Read an array and a number k. Print the k-th largest element when the array is sorted in descending order (equal values count separately). Example: in 3 2 1 5 6 4 the 2nd largest is 5.

Constraints

  • 1 <= k <= n <= 10^5

Examples

Input

6
3 2 1 5 6 4
2

Output

5

Solutions

Better approachTime O(n log n)Space O(n)

After sorting, the position of the answer is known. It is easy and takes O(n log n) time. A heap of size k can do it in O(n log k).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array and a number k.
 * Input   : n, then n integers, then k.
 * Output  : The k-th largest.
 * Approach: Sort the array.
 * Time    : O(n log n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(int[] a, int k) {
        // Step 1: Copy the array, so the input stays unchanged.
        int[] sorted = a.clone();

        // Step 2: Sort in ascending order.
        java.util.Arrays.sort(sorted);

        // Step 3: The k-th largest is the k-th element from the end.
        return sorted[sorted.length - k];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        int k = scanner.nextInt();
        System.out.println(solve(a, k));
    }
}
Hints (1)
  1. Which index is the k-th element from the end?