Where Will the Ball Fall - Problem

You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.

Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left:

  • A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.
  • A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.

We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box.

Return an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
Output: [1,-1,-1,-1,-1]
💡 Note: Ball 0 drops at column 0, follows right-pointing boards and exits at column 1. Other balls get stuck due to V-patterns or hitting walls.
Example 2 — Simple Case
$ Input: grid = [[-1]]
Output: [-1]
💡 Note: Single cell with left-pointing board. Ball hits the left wall immediately and gets stuck.
Example 3 — All Pass Through
$ Input: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]
Output: [-1,-1,-1,-1,-1,-1]
💡 Note: All balls get stuck because row 0 directs right but row 1 directs left, creating V-patterns everywhere.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 100
  • grid[i][j] is 1 or -1

Visualization

Tap to expand
Where Will the Ball Fall - Problem OverviewInput Grid1-1-11-1-11-1-1111Ball 0 → Column 1Balls 1,2 → StuckBall 3 → Column 3Output: [1, -1, -1, 3, -1, -1]Blue=Right(1), Red=Left(-1), V-patterns trap balls
Understanding the Visualization
1
Input Grid
2D grid with 1 (right-pointing) and -1 (left-pointing) diagonal boards
2
Ball Simulation
Each ball follows board directions, gets stuck on V-patterns or walls
3
Output Array
Final exit column for each ball, or -1 if stuck
Key Takeaway
🎯 Key Insight: A ball gets stuck when adjacent boards create a V-pattern (point toward each other) or when it hits a wall
Asked in
Amazon 25 Microsoft 18 Google 12
67.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen