Merge known bigrams in a sentence, leftmost first
I was asked this
No reports yet. Sign in to say where you were asked it.
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]:
...
-
textis a non-empty string of lowercase words separated by spaces. -
bigramsis 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 matchb a.
Rules:
- Read the words from left to right, and keep their original order in the output.
- When two adjacent words form a phrase in
bigrams, output them as one token, with the two words joined by one space. - Every other word is its own token.
- 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
