← Questions

Merge known bigrams in a sentence, leftmost first

0
SpaceXAICoding

Write a function that splits a sentence into tokens using a dictionary of known two-word phrases (bigrams).

def bigram_split(text: str, bigrams: list[str]) -> list[str]:
    ...
  • text is a non-empty string of lowercase words separated by spaces.
  • bigrams is a list of phrases. Each phrase is two lowercase words separated by one space, for example "machine learning". A bigram is directed: "a b" does not match b a.

Rules:

  1. Read the words from left to right, and keep their original order in the output.
  2. When two adjacent words form a phrase in bigrams, output them as one token, with the two words joined by one space.
  3. Every other word is its own token.
  4. If two possible matches overlap, take the one that starts further left. A word can be part of only one token.

Example 1

text    = "we use machine learning models"
bigrams = ["machine learning", "learning models"]
output  = ["we", "use", "machine learning", "models"]

"machine learning" and "learning models" share the word learning. The leftmost match wins, so models stays on its own.

Example 2

text    = "go go go"
bigrams = ["go go"]
output  = ["go go", "go"]

Constraints

  • 1 <= number of words <= 10^5
  • 0 <= len(bigrams) <= 10^5
  • Words contain only the letters a-z.

Aim for time linear in the length of the input.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding