#1706

Where Will the Ball Fall

Medium
ArrayMatrixSimulationSimulationDFSMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a depth-first search (DFS) approach to simulate the ball's path efficiently. By caching results for each column, we avoid redundant calculations, leading to a faster solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a helper function to simulate the ball's path for a given column.
  2. 2Step 2: Use memoization to store results for each column to avoid recalculating paths.
  3. 3Step 3: For each ball, call the helper function and store the results.
solution.py23 lines
1# Full working Python code
2
3def findBall(grid):
4    m, n = len(grid), len(grid[0])
5    memo = [-2] * n
6    def dfs(col):
7        if memo[col] != -2:
8            return memo[col]
9        position = col
10        for row in range(m):
11            direction = grid[row][position]
12            next_position = position + direction
13            if direction == 1 and (next_position >= n or grid[row][next_position] == -1):
14                memo[col] = -1
15                return -1
16            if direction == -1 and (next_position < 0 or grid[row][next_position] == 1):
17                memo[col] = -1
18                return -1
19            position = next_position
20        memo[col] = position
21        return position
22    result = [dfs(col) for col in range(n)]
23    return result

Complexity note: The time complexity is O(n) because each ball's path is calculated once and stored in memoization. The space complexity is O(n) due to the memo array used for caching results.

  • 1Understanding the grid's structure is crucial for simulating the ball's path.
  • 2Memoization can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.