Label Encode a List of String Categories

Basics
BasicsCategorical EncodingPythonGoogleMetaAmazon

Problem

Implement label_encode(labels) that maps each string in labels to an integer 0..K-1 based on alphabetically sorted unique categories, returning (encoded_ids, classes).

Why It Matters: Label encoding converts string class names into deterministic integer IDs required by scikit-learn estimators and cross-entropy losses.

Sample Inputs & Expected Outputs

Example 1 — Multiple categories

>>> label_encode(["dog", "cat", "dog", "bird"])
([2, 1, 2, 0], ["bird", "cat", "dog"])

Sorted classes: bird=0, cat=1, dog=2.

Example 2 — Single repeated category

>>> label_encode(["yes", "yes"])
([0, 0], ["yes"])

Only 1 unique class mapped to 0.

Example 3 — City names

>>> label_encode(["NYC", "LA", "SF", "LA"])
([1, 0, 2, 0], ["LA", "NYC", "SF"])

Alphabetical order: LA=0, NYC=1, SF=2.

Constraints & Edge Cases

  • Return (encoded_list, classes) where classes is sorted alphabetically.

Constraints & Evaluation Criteria

  • Return `(encoded_list, classes)` where `classes` is sorted alphabetically.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
['dog','cat','dog','bird']
Expected Output / Criteria
([2,1,2,0], ['bird','cat','dog'])