Where Will the Ball Fall — LeetCode 1706 Python Solution

MediumArrayMatrixSimulation
Problem
#1706
Reading time
3 min

The 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.

Example

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]
Explanation
This example is shown in the photo.

Python solution

Python
class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        def dfs(i: int, j: int) -> int:
            if i == m:
                return j
            if j == 0 and grid[i][j] == -1:
                return -1
            if j == n - 1 and grid[i][j] == 1:
                return -1
            if grid[i][j] == 1 and grid[i][j + 1] == -1:
                return -1
            if grid[i][j] == -1 and grid[i][j - 1] == 1:
                return -1
            return dfs(i + 1, j + 1) if grid[i][j] == 1 else dfs(i + 1, j - 1)

        m, n = len(grid), len(grid[0])
        return [dfs(0, j) for j in range(n)]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1706. Where Will the Ball Fall is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1706. Where Will the Ball Fall?
LeetCode 1706. Where Will the Ball Fall is rated Medium on LeetCode.
What is the time complexity of LeetCode 1706. Where Will the Ball Fall?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1706. Where Will the Ball Fall?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 1706. Where Will the Ball Fall cover?
LeetCode 1706. Where Will the Ball Fall is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview