Ctrl K

Balls Through a Slanted Box

Medium
A box is split into a grid box with m rows and n columns, and it is open at the top and the bottom. Every cell holds a diagonal board: - 1 means the board runs from the top-left corner to the bottom-right one and sends a ball to the right; - -1 means the board runs from the top-right corner to the bottom-left one and sends a ball to the left. One ball is dropped into the top of each column. In each cell the ball rolls along the board into the neighbouring column, one row lower. A ball gets stuck if a board steers it into a side wall of the box, or if two adjacent boards form a V shape (1 on the left and -1 on the right). Return an array of length n: for the ball dropped into column j, the column it falls out of at the bottom, or -1 if it gets stuck.
Example 1
box=[[1, -1, 1], [1, 1, -1]] → [-1, -1, -1]

The balls from columns 0 and 1 roll straight into the V formed by boards 1 and -1 and get stuck. The ball from column 2 runs into the right wall.

Example 2
box=[[1, 1, 1, 1], [-1, -1, -1, -1]] → [0, 1, 2, -1]

In the first row every ball except the rightmost one (it gets stuck at the wall) shifts right, and in the second row it shifts back left. Result: [0, 1, 2, -1].

Example 3
box=[[-1, -1], [1, 1]] → [-1, 1]
Constraints
  • 1 ≤ m, n ≤ 100
  • box[i][j] is 1 or -1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSpiral Readout MediumSpiral-Numbered Square MediumNext Step of a Cell Colony MediumZigzag Diagonal Sweep MediumMatch-Three Cascade Medium
loading Python…
Input
box=[[1, -1, 1], [1, 1, -1]]
Expected
[-1, -1, -1]

Run checks the first 3 tests in your browser. Submit checks all 68 tests on the server, hidden ones included.