First and Last K Words From a Stream
Problem statement
Words arrive in the order given by words. Return two lists: the first k retained words and the last k retained words.
If distinct is false, retain every occurrence. If distinct is true, retain only the first occurrence of each word, preserving first-occurrence order.
When fewer than k words remain, return all of them in both lists. The two returned lists may overlap.
Function
firstAndLastKWords(words: String[], k: int, distinct: boolean) → String[][]Examples
Example 1
words = ["a","b","c","d"]k = 2distinct = falsereturn = [["a","b"],["c","d"]]The first two and final two stream occurrences are returned.
Example 2
words = ["a","b","a","c"]k = 2distinct = truereturn = [["a","b"],["b","c"]]The retained distinct sequence is [a,b,c].
Example 3
words = ["one"]k = 3distinct = falsereturn = [["one"],["one"]]Only one word is available, so both results contain it.
Constraints
1 <= words.length <= 100000.1 <= k <= 100000.- Every word has length from
1through100. - Words contain lowercase English letters.