Where Will the Ball Fall - Problem
Imagine a pinball machine box with diagonal boards that redirect balls left or right! You have an m × n grid representing this box, where each cell contains a diagonal board:
- Value 1: Board redirects ball to the right (top-left to bottom-right diagonal)
- Value -1: Board redirects ball to the left (top-right to bottom-left diagonal)
Drop one ball from the top of each column. Each ball will either:
- ✅ Fall out the bottom - reaching the bottom row and exiting
- ❌ Get stuck - hitting a "V" shape pattern or bouncing into a wall
Goal: For each ball dropped from column i, return which column it exits from at the bottom, or -1 if it gets stuck.
Think of it as simulating gravity with bouncing balls in a maze of diagonal mirrors!
Input & Output
example_1.py — 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 from column 0 exits at column 1. Balls from columns 1-4 get stuck due to V-shaped traps or wall collisions.
example_2.py — Single Row
$
Input:
grid = [[-1]]
›
Output:
[-1]
💡 Note:
The single ball hits the left wall immediately and gets stuck.
example_3.py — All Right Direction
$
Input:
grid = [[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 slide right. Only the rightmost ball can exit, others hit the right wall.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Place ball at top of each column
2
Move Down
Ball follows diagonal board direction
3
Check Collision
Detect walls and V-traps
4
Result
Record exit column or -1 if stuck
Key Takeaway
🎯 Key Insight: This is a pure simulation problem where we trace each ball's path through diagonal boards, checking for collision conditions at each step.
Time & Space Complexity
Time Complexity
O(m × n)
For each of n balls, we simulate at most m rows
✓ Linear Growth
Space Complexity
O(1)
Only using variables to track current position
✓ Linear Space
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- grid[i][j] is 1 or -1
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code