easy +10 pts

One Hot Encode Labels

Convert a list of categorical labels into a one-hot encoded matrix.

Write a function `one_hot_encode(labels)` that takes a list of strings `labels` and returns a list of lists (a matrix) where each row corresponds to the input label and is a one-hot encoded vector. The vector length is the number of unique labels, and the order of dimensions is the sorted order of the unique labels. For each label, the vector has a 1 in the position of the label in that sorted order, and 0 elsewhere. The input list will contain only strings and will not be empty. The function should return a list of lists of integers. Examples: - `one_hot_encode(["red", "blue", "red"])` returns `[[0, 1], [1, 0], [0, 1]]` because unique labels sorted are `["blue", "red"]`, so "blue" maps to index 0 and "red" maps to index 1. - `one_hot_encode(["b", "a"])` returns `[[0, 1], [1, 0]]`.

Constraints

- `1 <= len(labels) <= 1000` - Each label is a string of lowercase letters, length 1 to 20. - The labels are not necessarily unique. - Your solution should have time complexity O(n * k) where n is the length of labels and k is the number of unique labels.

Example

>>> one_hot_encode(["red", "blue", "red"])
[[0, 1], [1, 0], [0, 1]]
>>> one_hot_encode(["b", "a"])
[[0, 1], [1, 0]]
>>> one_hot_encode(["x"])
[[1]]
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First find the sorted unique labels.
Create a mapping from each label to its index in the sorted unique list.
For each label, build a vector of zeros with length equal to the number of unique labels and set the mapped index to 1.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.