Problem · Array
Select First or Last K Stream Words
Learn this problemProblem statement
You are given a finite stream of lowercase words, an integer k, and one of four modes:
FIRST: return the firstkwords.LAST: return the lastkwords.FIRST_DISTINCT: scan from left to right and return the firstkdifferent words, keeping their first-occurrence order.LAST_DISTINCT: keep at most one copy of each word, select thekwords whose final occurrences are latest, and return them in the order of those final occurrences.
For a distinct mode, if the stream contains fewer than k different words, return all different words in the required order.
Function
selectStreamWords(words: String[], k: int, mode: String) → String[]Examples
Example 1
words = ["ant","bee","ant","cat","dog"]k = 2mode = "FIRST"return = ["ant","bee"]The first two stream items are returned, including any repetitions that would occur there.
Example 2
words = ["ant","bee","ant","cat","dog"]k = 3mode = "LAST"return = ["ant","cat","dog"]The final three arrivals occupy indices 2 through 4.
Example 3
words = ["ant","bee","ant","cat","bee"]k = 3mode = "LAST_DISTINCT"return = ["ant","cat","bee"]The final occurrences of ant, cat, and bee are at indices 2, 3, and 4, respectively.
Constraints
1 <= words.length <= 2000001 <= k <= words.length- Each word contains
1to40lowercase English letters. modeis exactlyFIRST,LAST,FIRST_DISTINCT, orLAST_DISTINCT.- The total number of characters in
wordsis at most1000000.