One-hot encode an integer array

0
Sign in

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 i has a 1 in the column for arr[i] and 0 everywhere 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.

Reconstructed from the reported question; details may differ from what interviewers ask.

NetflixCodingEasy

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.