Back to Practice
#0183

One-Hot Encode Integer Labels

MediumNumPy25 min20 XP

Problem

Given integer labels and num_classes, return a matrix with one 1 per row at the label index.

Why This Matters

One-hot matrices appear in classification labels, categorical features, and neural-network targets.

Function Signature

def one_hot(labels, num_classes):

Examples

Example 1
Inputlabels = [2, 0, 1], num_classes = 3
Output[[0,0,1],[1,0,0],[0,1,0]]

Each row marks the class index for that label.

Constraints

  • Return the exact requested result.
  • Handle common edge cases.
  • Keep the solution readable before optimizing.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputlabels = [2, 0, 1], num_classes = 3
Expected[[0,0,1],[1,0,0],[0,1,0]]

Each row marks the class index for that label.

Hidden Test Categories
minimal inputrepeated valueslarger realistic input