Problem · String
Longest Dictionary Tokenization
Learn this problemProblem statement
You are given a text string and a dictionary of token-to-id mappings. Starting from the beginning of text, repeatedly choose the longest dictionary token that matches the current position and output its id. If no dictionary token matches, output the current character itself and advance by one character.
Return the sequence of emitted ids and literal characters.
Function
encodeWithDictionary(text: String, dictionary: String[][]) → String[]Examples
Example 1
text = "applepie"dictionary = [["app","B"],["apple","A"],["pie","P"]]return = ["A","P"]apple is preferred over app because it is the longest match at index 0.
Example 2
text = "xabcd"dictionary = [["ab","1"],["abc","2"],["bc","3"]]return = ["x","2","d"]The first character has no match, then abc is the longest token starting at index 1.
Constraints
If multiple dictionary entries have the same token, use the first mapping provided. The tokenization is greedy and scans left to right.
More Google problems
- Longest Subarray with Sum at Most KOA · Seen Jul 2026
- Count Prefix Matches in a Sorted ArrayONSITE INTERVIEW · Seen Jul 2026
- Decode StringONSITE INTERVIEW · Seen Jul 2026
- Phone Keypad Letter CombinationsONSITE INTERVIEW · Seen Jul 2026
- Split a Log Outside QuotesONSITE INTERVIEW · Seen Jul 2026
- Ad Score Scheduler With DelayONSITE INTERVIEW · Seen Jul 2026
- Alternating-Color Binary Tree RootsONSITE INTERVIEW · Seen Jul 2026
- Route Pattern MatcherONSITE INTERVIEW · Seen Jul 2026