Problem · Matrix

Bouncing Diagonal Weights

Learn this problem
MediumDatabricks logoDatabricksINTERNOA

Problem statement

You are given a non-empty square integer matrix matrix.

For every starting cell in the leftmost column, trace a path that visits exactly one cell in each column:

  • The path initially moves one row up and one column right.
  • When the path reaches the top row, it changes direction and continues one row down and one column right until it reaches the rightmost column.

The weight of a starting cell is the sum of the matrix values on its path.

For every starting cell, form the pair (weight, leftmost value). Sort all pairs in ascending lexicographic order: first by weight, then by leftmost value when the weights are equal. Return the second value from each sorted pair.

Function

Diagonalweights(matrix: int[][]) → int[]

Examples

Example 1

matrix = [[2, 3, 2], [0, 2, 5], [1, 0, 1]]return = [1, 2, 0]

The paths starting in rows 0, 1, and 2 have weights 2 + 2 + 1 = 5, 0 + 3 + 5 = 8, and 1 + 2 + 2 = 5.

The corresponding pairs are (5, 2), (8, 0), and (5, 1). After sorting, they are (5, 1), (5, 2), and (8, 0), so the answer is [1, 2, 0].

Example 2

matrix = [[1, 3, 2, 5], [3, 2, 5, 0], [9, 0, 1, 3], [6, 1, 0, 8]]return = [1, 9, 3, 6]

The four path weights are 1 + 2 + 1 + 8 = 12, 3 + 3 + 5 + 3 = 14, 9 + 2 + 2 + 0 = 13, and 6 + 0 + 5 + 5 = 16.

The sorted pairs are (12, 1), (13, 9), (14, 3), and (16, 6), so the answer is [1, 9, 3, 6].

Constraints

  • matrix is a non-empty square matrix of integers.

More Databricks problems

drafts saved locally
public int[] Diagonalweights(int[][] matrix) {
  // write your code here
}
matrix[[2, 3, 2], [0, 2, 5], [1, 0, 1]]
expected[1, 2, 0]
checking account