Pivot Long to Wide

HardData EngineeringArrayMathSortingMatrixSQL

Description

Given an array of [row, column, value] triples, pivot the long-format data into a wide 2D table. The rows of the output correspond to the sorted distinct row keys and the columns to the sorted distinct column keys; each cell holds the matching value, or 0 if no triple covers it. Assume at most one triple per (row, column).

Examples

Input:[[0,0,5],[0,1,3],[1,1,7]]
Output:[[5,3],[0,7]]
Explanation:

The long triples are reshaped into a grid indexed by the sorted distinct row and column keys, with any unfilled cell defaulting to zero.

Input:[[0,0,1]]
Output:[[1]]
Explanation:

The long triples are reshaped into a grid indexed by the sorted distinct row and column keys, with any unfilled cell defaulting to zero.

Input:[[0,0,1],[1,1,2],[2,2,3]]
Output:[[1,0,0],[0,2,0],[0,0,3]]
Explanation:

The long triples are reshaped into a grid indexed by the sorted distinct row and column keys, with any unfilled cell defaulting to zero.

Constraints

  • 1 ≤ number of triples ≤ 10⁴

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.