Find Kth Largest Integer in the Array

Find the kth largest number in an array of numbers written as strings, some too long for a long.

Given an array of strings nums, where each string is a non-negative integer with no leading zeros, and an integer k, return the string of the kth largest integer. Equal numbers count separately: in ["1", "2", "2"], the largest and the 2nd largest are both "2", and the 3rd largest is "1". The numbers can have up to 100 digits, so they do not fit in a long.

Example 1
Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation: sorted by value: 3, 6, 7, 10. The 4th largest is 3.
Example 2
Input: nums = ["2","21","12","1"], k = 3
Output: "2"
Example 3
Input: nums = ["0","0"], k = 2
Output: "0"
Solution

The Idea

Think of a scoreboard that shows only the top three scores. A new score goes on the board, and if the board now has four, the lowest one falls off. At any moment, the third largest score so far is simply the lowest one on the board. Finding the kth largest number works the same way, with a board of k places.

Example 2 adds a twist: the numbers are strings, "2", "21", "12" and "1", and k = 3. By value they are 1, 2, 12, 21, so the 3rd largest is 2. Java compares strings as text, character by character, and since "1" comes before "2", text order is "1", "12", "2", "21". As text, "12" counts as smaller than "2".

So two questions come up. How do we compare two numbers that are written as strings? And how do we keep the k largest without much work?

The strings have no leading zeros, so more digits always means a bigger number. "21" has two digits and "2" has one, so 21 is the bigger number. Only when two strings have the same length, such as "12" and "21", does comparing them character by character give the right answer.

For the board, we need a container that hands out its smallest item quickly, because that is the item that falls off. A container that keeps its smallest item on top, ready to be read or removed, and takes in a new item in a few steps, is called a min-heap. Look at the picture below, which follows Example 2.

Example 2 with k = 3. The strings 2, 21 and 12 are added to the heap, and 2 stays the smallest value kept. Adding 1 makes four strings, one too many, so the smallest, 1, is removed. The smallest value kept is then 2, the 3rd largest.

In the rows labelled add "2", add "21" and add "12", each string goes in, and 2 stays in the orange box as the smallest value kept. In the row labelled add "1", the heap has 4 strings, one too many for k = 3, so the smallest, 1, is removed. The orange box still holds 2, and 2 is the answer.

So the kth largest number is the top of a min-heap that keeps the k largest numbers seen so far, ordered by value rather than as text.

Solution Approach

Turning that idea into code means settling three things: how to compare two numbers written as strings, which heap to use and when to remove from it, and how equal numbers are counted.

Comparing numbers written as strings

Why not turn each string into a number first? A long stops at 9,223,372,036,854,775,807, which has 19 digits, and these strings can have 100. Long.parseLong on a string of twenty nines throws a NumberFormatException. BigInteger could hold such numbers, but comparing the strings directly needs no conversion at all.

The comparison takes two steps. If the lengths differ, the longer string is the bigger number. If the lengths are equal, the string method compareTo compares the two strings character by character, and since the characters '0' to '9' are stored in that order, this matches the order of the numbers.

Keeping the k largest in a PriorityQueue

Which Java class gives a min-heap? PriorityQueue, in java.util, keeps its smallest item on top. Given a Comparator, an object that decides which of two items is smaller, it uses that order instead of the items' own. Three of its methods matter here: add puts an item in, poll removes the top, and peek reads the top without removing it.

When should a string leave the heap? As soon as the heap holds k + 1 strings, k of its strings are at least as big as its smallest one. That smallest string can never be the kth largest, and strings added later only push it further down, so poll removes it right away.

Sorting the whole array by value and taking the kth string from the end works too, and is shorter to write. But it sorts all n strings of the array, where n is the length of nums, while the heap never holds more than k + 1. When k is small next to n, each add or poll costs about log k comparisons instead of the log n a sort pays per string.

Counting equal numbers

What happens to a number that appears twice? Unlike a set, a PriorityQueue keeps equal items as separate entries. In Example 3, both "0" strings stay in the heap, so the 2nd largest is "0".

Java Solution

The method kthLargestNumber works in these steps:

  1. First, the comparator BY_VALUE decides which of two strings is the smaller number. When the lengths differ, it compares them with Integer.compare; when they are equal, it falls back to a.compareTo(b).
  2. Create the min-heap topK, a PriorityQueue built with BY_VALUE, so the string with the smallest value sits on top.
  3. A loop goes over nums and adds each string num to topK. If topK now holds more than k strings, poll removes the smallest.
  4. After the loop, topK holds the k largest strings, and peek returns the smallest of them, which is the kth largest.

The main method runs the three examples, then a 30-digit and a 20-digit number, both too long for a long, with k = 1 and 2. Last comes an array that has 9 twice, with k = 2.

Java
import java.util.Comparator;
import java.util.PriorityQueue;

public class KthLargestInteger {

    // Compares two numbers written as strings, by value: no leading zeros,
    // so a longer string is a bigger number; equal lengths compare digit by digit.
    static final Comparator<String> BY_VALUE = (a, b) -> a.length() != b.length()
            ? Integer.compare(a.length(), b.length())
            : a.compareTo(b);

    public static String kthLargestNumber(String[] nums, int k) {
        PriorityQueue<String> topK = new PriorityQueue<>(BY_VALUE); // min-heap: smallest on top
        for (String num : nums) {
            topK.add(num);
            if (topK.size() > k) {
                topK.poll();                  // one too many: drop the smallest
            }
        }
        return topK.peek();                   // the smallest of the k largest
    }

    public static void main(String[] args) {
        System.out.println(kthLargestNumber(new String[] {"3", "6", "7", "10"}, 4));
        System.out.println(kthLargestNumber(new String[] {"2", "21", "12", "1"}, 3));
        System.out.println(kthLargestNumber(new String[] {"0", "0"}, 2));
        String[] big = {"5", "123456789012345678901234567890", "99999999999999999999"};
        System.out.println(kthLargestNumber(big, 1));
        System.out.println(kthLargestNumber(big, 2));
        System.out.println(kthLargestNumber(new String[] {"5", "9", "9", "1"}, 2));
    }
}

Running it prints:

Output
3
2
0
123456789012345678901234567890
99999999999999999999
9

Look at the second line: Example 2 gives 2, as in the picture. With new PriorityQueue<>(), which uses the strings' own text order, the same loop returns "12" for Example 2 instead, because as text "12" sorts before "2".

The fourth and fifth lines come from the two long numbers. The 30-digit string wins with k = 1, and the twenty nines come 2nd. As text, the twenty nines would win, because their first character, 9, comes after 1. Comparing lengths first puts them in the right order.

The last line is 9: in ["5", "9", "9", "1"], both 9 strings stay in the heap, so the 2nd largest is the other 9, not 5.

Complexity

Each of the n strings goes into the heap once, and the heap never grows past k + 1 strings.

  • Time: O(n · D · log k), because each of the n strings costs an add and maybe a poll of about log k comparisons, and a comparison reads up to D digits, the longest string's length.
  • Space: O(k), because the heap holds at most k + 1 references to the caller's strings, not copies of them.

The same size-k heap answers a new query each time a number arrives in Kth Largest Element in a Stream.