v9.1.1
Menu

Character-Level Tokenizer

easyFREETokenization AlgorithmsLLM 1: Foundations

Build a character-level tokenizer that converts text to token IDs and back.

Given a text string, build a vocabulary mapping each unique character to an integer ID (sorted by character order, starting from 0). Then encode the text as a list of IDs and decode it back.

Implement char_tokenizer(text) that returns a tuple (encoded_ids, decoded_text): a list of integer IDs and the decoded string.

Input:

  • A single line of text

Output (as printed by the tests):

  • Line 1: The encoded token IDs (space-separated)
  • Line 2: The decoded text (should match input)

Example

Input
hello
Output
1 0 2 2 3
hello
Reasoning
  • The input is the string hello: five characters, but only four distinct ones, since l appears twice.
  • The vocabulary orders the distinct characters by Unicode code point: e =101=101, h =104=104, l =108=108, o =111=111. Numbering them from 0 gives e →0\to 0, h →1\to 1, l →2\to 2, o →3\to 3.
  • Encoding replaces each character of the text, in its original position, with its ID: h, e, l, l, o becomes 1,0,2,2,31, 0, 2, 2, 3, which is the first output line 1 0 2 2 3.
  • Decoding reads the same table in the other direction: 1→1 \to h, 0→0 \to e, 2→2 \to l, 2→2 \to l, 3→3 \to o, giving back hello.
  • Notice that the IDs follow alphabetical order, not order of first appearance. That is why h, the first letter, gets ID 1 rather than 0. Repeated characters share one ID, so the vocabulary size is 4 while the encoded list has length 5. A space would get an ID too (code point 32, so it sorts before any letter).

Constraints

  • Characters are sorted by their Unicode code point for ID assignment
  • IDs start from 0
  • Space characters are included in the vocabulary
  • Output IDs space-separated on line 1, decoded text on line 2

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.