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 numsk["1", "2", "2"]long
Example 1
Output: "3"
Explanation: sorted by value: 3, 6, 7, 10. The 4th largest is 3.
Example 2
Output: "2"
Example 3
Output: "0"
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.
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 longLong.parseLongNumberFormatExceptionBigInteger
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
Keeping the k largest in a PriorityQueue
Which Java class gives a min-heap? PriorityQueuejava.utilComparatoraddpollpeek
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
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 numsaddpoll
Counting equal numbers
What happens to a number that appears twice? Unlike a set, a PriorityQueue
Java Solution
The method kthLargestNumber
- First, the comparator
decides which of two strings is the smaller number. When the lengths differ, it compares them withBY_VALUE ; when they are equal, it falls back toInteger.compare .a.compareTo(b) - Create the min-heap
, atopK built withPriorityQueue , so the string with the smallest value sits on top.BY_VALUE - A loop goes over
and adds each stringnums tonum . IftopK now holds more thantopK strings,k removes the smallest.poll - After the loop,
holds the k largest strings, andtopK returns the smallest of them, which is the kth largest.peek
The mainlong
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:
3
2
0
123456789012345678901234567890
99999999999999999999
9
Look at the second line: Example 2 gives 2, as in the picture. With new PriorityQueue<>()
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"]
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
and maybe aadd of about log k comparisons, and a comparison reads up to D digits, the longest string's length.poll - 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