Here's my algorithm:
(a) Make a WordOccurrence class that contains a String sentence and an int numberOfOccurrences. Let's assume the sentence has n words. Make this class implement Comparable, and make the comparator the numberOfOccurrences first, and then (arbitrarily,) the alphabetical (natural) ordering of the word second.
(b) Iterate through sentence with .split(‘ ‘) (or do it in place with iteration to save space). Create a new WordOccurrence object for each unique word, updating its occurrence and placing all WordOccurrence objects into a TreeMap<WordOccurrence>.
(c) Create a new WordOccurrence object for each unique word, placing all WordOccurrence objects into a TreeMap<WordOccurrence> (and updating words' occurrences along the way).
(d) Call highestKey() on the TreeMap, and place the returned word into a resultant list. Then call lowerKey with the previously returned word (k - 1) times, placing the words into the same resultant list.
(e) Return the resultant list.
My question: What is the runtime of this? This is my understanding:
Step (b) takes O(n) time.
Step (c) takes O(n*log(n)), as for each of the n words, insertion is O(log n).
Step (d) takes O(k*log(n)), as each call of highestKey() or lowerKey() takes O(log n) time.
So the total runtime would be: O(n + n*log(n) + k*log(n), which is O(n*log n).
Is there a tighter bound for this algorithm, or a way to get it to O(n)?
Thanks.