TopK
TopK Strings with longest length
public static List<String> topK(int k, Iterator<String> iter) {
PriorityQueue<String> miniHeap = new PriorityQueue<>(k, new Comparator<String>(){
@Override
public int compare(String s1, String s2){
return Integer.compare(s1.length(), s2.length());
}
});
while(iter.hasNext()){
String s = iter.next();
if (s.length() > miniHeap.peek().length()) {
miniHeap.add(s);
}
}
return new ArrayList<>(miniHeap);
}378 Kth Smallest Number in a Sorted Matrix
Find the kth smallest number in at row and column sorted matrix.

Pair class to store x and y index
Put numbers in first column or first row
Poll number and add new number based on previous row, loop k-1 times
373 Find K Pairs with Smallest Sums
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.

Use a minHeap to store sum
Pull out the sum and put new sum based on previous nums1 + 1
692 Top K frequent word
Order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.
PriorityQueue: put the String in reverse compareTo order if they have same frequency
Time O(nlogk)
Bucket with list List[] bucket, bucket[i] is the frequency of string
Time avg O(nlogk), best O(klogk), worst O(nlogn)
Trie[] bucket, bucket[i] store the strings in same frequency
Time: O(n * avgLenOfWord)
1244. TopK Leaderboard
Design a Leaderboard class, which has 3 functions:
addScore(playerId, score): Update the leaderboard by addingscoreto the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the givenscore.top(K): Return the score sum of the topKplayers.reset(playerId): Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function.
O(nlogk)
O(KlogN)
Last updated
Was this helpful?