← Questions

Sort rows by the weight of a bouncing diagonal path

0
DatabricksCodingLast asked Aug 2024

A coding interview question asked in Databricks's online assessment, last asked Aug 2024. It tests matrix, sorting and simulation.

In a square matrix, start a path at each cell of the first column. The path visits exactly one cell per column: it moves one row up and one column right each step, and once it reaches the top row it turns and moves one row down and one column right until it reaches the last column. A start cell's weight is the sum of the values on its path. Sort the start cells by weight, with ties broken by the start cell's own value, and return the start cells' values in that order.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • sort_by_bounce_weight(matrix: list[list[int]]) -> list[int] — sort the pairs (weight, matrix[r][0]) ascending and return the second element of each.

Example

sort_by_bounce_weight([[2, 3, 2],
                       [0, 2, 5],
                       [1, 0, 1]])                ->  [1, 2, 0]
# row 0: 2 + 2 + 1 = 5; row 1: 0 + 3 + 5 = 8; row 2: 1 + 2 + 2 = 5
# pairs (5, 2), (8, 0), (5, 1) sort to (5, 1), (5, 2), (8, 0)

sort_by_bounce_weight([[1, 3, 2, 5],
                       [3, 2, 5, 0],
                       [9, 0, 1, 3],
                       [6, 1, 0, 8]])             ->  [1, 9, 3, 6]
# weights 12, 14, 13, 16

Constraints

  • The matrix is square and non-empty; values are integers.
  • A path that starts in the top row turns immediately and goes down.

Clarifying questions

  • Does a path that starts on the top row go down from the first step?
  • Can a path hit the bottom row before the last column? (No: it goes up at most r rows, then down, and there are only n columns.)
  • How are ties broken when both weight and start value are equal?

What a strong answer covers

  • A simulation per start row with a direction flag; O(n) per path, O(n^2) total, plus the sort.
  • Correct turning at row 0, including a start in row 0.
  • Sorting by the tuple (weight, start value).
  • Tests: a 1 × 1 matrix, a start in the top row, equal weights.

Follow-ups

  • Paths also bounce off the bottom row. Generalize the walk.
  • Compute all weights in O(n^2) for a very large n without per-path loops in Python (vectorize, or reuse sums along diagonals).
  • Return the path with the largest weight.

Where it's asked

What it tests

matrix · sorting · simulation

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