FastPrepSelect First or Last K Stream Words
Problem · Array

Select First or Last K Stream Words

Learn this problem
MediumGoogle logoGoogleNEW GRADPHONE SCREEN
See Google hiring insights

Problem statement

You are given a finite stream of lowercase words, an integer k, and one of four modes:

  • FIRST: return the first k words.
  • LAST: return the last k words.
  • FIRST_DISTINCT: scan from left to right and return the first k different words, keeping their first-occurrence order.
  • LAST_DISTINCT: keep at most one copy of each word, select the k words 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 <= 200000
  • 1 <= k <= words.length
  • Each word contains 1 to 40 lowercase English letters.
  • mode is exactly FIRST, LAST, FIRST_DISTINCT, or LAST_DISTINCT.
  • The total number of characters in words is at most 1000000.

More Google problems

drafts saved locally
public String[] selectStreamWords(String[] words, int k, String mode) {
    // Write your code here.
}
words["ant","bee","ant","cat","dog"]
k2
mode"FIRST"
expected["ant", "bee"]
checking account