FastPrepFirst and Last K Words From a Stream

First and Last K Words From a Stream

Google logoGoogle● EasyNEW GRADPHONE SCREEN
Learn

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 1 through 100.
  • Words contain lowercase English letters.

More Google problems

See Google hiring insights
public String[][] firstAndLastKWords(String[] words, int k, boolean distinct) {
    // write your code here
}
words["a","b","c","d"]
k2
distinctfalse
expected[["a", "b"], ["c", "d"]]
Checking account…