Build a Word-to-ID Vocabulary Dictionary

Basics
BasicsTokenizationVocabularyOpenAIAnthropicGoogle

Problem

Implement build_vocab(tokens) taking a list of string tokens and returning a dictionary mapping '<PAD>' to 0, '<UNK>' to 1, and every unique remaining token—sorted alphabetically—to consecutive integer IDs starting at 2.

Why It Matters: Neural language models operate on integer token IDs, reserving fixed slots (0 for padding, 1 for out-of-vocabulary words) so batches align deterministically.

Function Signature

def build_vocab(tokens: list[str]) -> dict[str, int]:
    """Return word->id dict with <PAD>=0, <UNK>=1, then sorted unique tokens."""

Sample Input & Output

Example 1: Standard Token List With Duplicates

Input:

tokens = ["dog", "cat", "dog", "bird"]

Expected Output:

{"<PAD>": 0, "<UNK>": 1, "bird": 2, "cat": 3, "dog": 4}

Explanation: Duplicates ('dog') are deduplicated, and unique words are sorted alphabetically starting at ID 2.

Example 2: Input Containing Special Tokens

Input:

tokens = ["<UNK>", "ai", "<PAD>", "ai"]

Expected Output:

{"<PAD>": 0, "<UNK>": 1, "ai": 2}

Explanation: <PAD> and <UNK> stay pinned at 0 and 1 and are never duplicated at higher IDs.

Constraints & Edge Cases

  • '<PAD>' -> 0, '<UNK>' -> 1, followed by sorted unique words starting at 2.
  • Empty input [] must still return {'<PAD>': 0, '<UNK>': 1}.
  • Sorting guarantees deterministic vocabulary IDs across runs.

Constraints & Evaluation Criteria

  • `'<PAD>' -> 0`, `'<UNK>' -> 1`, followed by sorted unique words starting at `2`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['cat', 'sat', 'cat']
Expected Output / Criteria
{'<PAD>':0,'<UNK>':1,'cat':2,'sat':3}