One-hot encode an integer array
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Netflix. It tests arrays, hash map and sorting.
Write one_hot(arr: list[int]) -> list[list[int]] that returns the one-hot encoding of an integer array as a 2D list.
- The matrix has one row per element of
arr, in the same order. - It has one column per distinct value in
arr. Columns are ordered by value, smallest first. - Row
ihas a1in the column forarr[i]and0everywhere else.
An empty input returns an empty list.
Constraints
0 <= len(arr) <= 10^5-10^9 <= arr[i] <= 10^9- The number of distinct values times
len(arr)fits in memory.
Example 1
arr = [4, 1, 4, 7]
columns (sorted distinct values): [1, 4, 7]
output:
[[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
Example 2
arr = [3, 3, -2]
columns: [-2, 3]
output: [[0, 1], [0, 1], [1, 0]]
Possible next parts: decode a matrix back to the values, return a compact representation when there are many distinct values, and encode new data with columns fixed from earlier data.
Clarifying questions
- Should the column order (the sorted distinct values) be returned too, so the matrix can be read back?
- Is an empty input
[], with no columns at all? - Is a plain Python 2D list required, or would a NumPy array or a sparse format be acceptable?
- How large can the distinct count get relative to
len(arr)?
What a strong answer covers
- Sorts the distinct values once and maps each value to its column index with a dictionary:
O(n log n)for the sort, thenO(1)per element. - Builds each row as a list of zeros with one
1;O(n * d)time and memory forddistinct values, which is the size of the output. - Handles negative values and repeats, and returns
[]for an empty input. - Notes that a dense matrix wastes memory when
dis large, and that storing one column index per row carries the same information. - Tests both examples, a single repeated value, and all values distinct.
Follow-ups
- Decode a matrix back to the original values.
- Return a sparse representation when there are many distinct values.
- Fit the columns on one array, then encode new data with them, deciding what to do with unseen values.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
