← Questions

One-hot encode an integer array

0
NetflixCoding

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 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.

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, then O(1) per element.
  • Builds each row as a list of zeros with one 1; O(n * d) time and memory for d distinct 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 d is 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

arrays · hash map · sorting · ml basics

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding