r/Hack2Hire • u/Hack2hire • 13h ago
Screening Anthropic Screening: String Tokenization
You get a string text and an array dictionary of entries in the form "<key>:<id>", where key is a token string and id is its identifier. All keys are unique, 1 <= text.length <= 10^9 and 0 <= dictionary.length <= 10^9. Split text into tokens and return them as a list of strings.
At each position, pick the longest dictionary key that starts there, output its id, and continue from the first character after it. If no key starts at the current position, output that single character as a literal and move forward by one.
Follow-up
Handle a dictionary too large to keep in memory, or cut trie space when many keys share prefixes.
Example
Input: text = "applepiepear", dictionary = ["app:10", "apple:20", "pie:30"] Output: ["20", "30", "p", "e", "a", "r"]
Explanation:
- At index 0 both "app" and "apple" match, and the longer "apple" wins, so the output starts with "20".
- "pie" matches next, giving "30".
- No key starts at any of the last four characters, so each is output as itself.
Suggested Approach
- Insert every dictionary key into a trie, storing the key's
idon the node where the key ends. - Walk
textleft to right with an index pointer. - At each position, follow the trie as far as the text matches, remembering the last node that ended a complete key.
- If a key ended along the way, output its
idand move the pointer past that key. Otherwise output the current character and move forward by one.
Time & Space Complexity
- Time: O(N × L), where N is the length of
textand L is the length of the longest dictionary key. Each position needs at most L steps to find its longest match. - Space: O(S + N), where S is the total number of characters across all dictionary keys (the trie) and N is the length of
text.
Targeting Anthropic interviews? We track their most-asked question patterns at Hack2Hire. Practice this question here → Practice Question Here
Join the community to see more interview experiences from real candidates → Hack2Hire Forum
Compiled from publicly available platforms and community-shared experiences.