Skip to main content

Twisted Mirror Path Count - Solution & Explanation

MediumArrayDynamic ProgrammingMatrix5 min readAsked at: Microsoft, Google
Practice this problem

Problem Statement

Given an m x n binary grid grid where:

  • grid[i][j] == 0 represents an empty cell, and
  • grid[i][j] == 1 represents a mirror.

A robot starts at the top-left corner of the grid (0, 0) and wants to reach the bottom-right corner (m - 1, n - 1). It can move only right or down. If the robot attempts to move into a mirror cell, it is reflected before entering that cell:

  • If it tries to move right into a mirror, it is turned down and moved into the cell directly below the mirror.
  • If it tries to move down into a mirror, it is turned right and moved into the cell directly to the right of the mirror.

If this reflection would cause the robot to move outside the grid boundaries, the path is considered invalid and should not be counted.

Return the number of unique valid paths from (0, 0) to (m - 1, n - 1).

Since the answer may be very large, return it modulo 109 + 7.

Note: If a reflection moves the robot into a mirror cell, the robot is immediately reflected again based on the direction it used to enter that mirror: if it entered while moving right, it will be turned down; if it entered while moving down, it will be turned right. This process will continue until either the last cell is reached, the robot moves out of bounds or the robot moves to a non-mirror cell.

 

Example 1:

Input: grid = [[0,1,0],[0,0,1],[1,0,0]]

Output: 5

Explanation:

Number Full Path
1 (0, 0) → (0, 1) [M] → (1, 1) → (1, 2) [M] → (2, 2)
2 (0, 0) → (0, 1) [M] → (1, 1) → (2, 1) → (2, 2)
3 (0, 0) → (1, 0) → (1, 1) → (1, 2) [M] → (2, 2)
4 (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2)
5 (0, 0) → (1, 0) → (2, 0) [M] → (2, 1) → (2, 2)
  • [M] indicates the robot attempted to enter a mirror cell and instead reflected.

Example 2:

Input: grid = [[0,0],[0,0]]

Output: 2

Explanation:

Number Full Path
1 (0, 0) → (0, 1) → (1, 1)
2 (0, 0) → (1, 0) → (1, 1)

Example 3:

Input: grid = [[0,1,1],[1,1,0]]

Output: 1

Explanation:

Number Full Path
1 (0, 0) → (0, 1) [M] → (1, 1) [M] → (1, 2)
(0, 0) → (1, 0) [M] → (1, 1) [M] → (2, 1) goes out of bounds, so it is invalid.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 500
  • grid[i][j] is either 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0

Approach Overview

Problem Overview: You are given a matrix where each cell may contain a mirror that twists the direction of movement. Starting from the top-left cell, you need to count how many valid ways reach the bottom-right cell while respecting how mirrors redirect the path.

Approach 1: Brute Force DFS Traversal (Exponential Time, O(2^(m+n)) time, O(m+n) space)

The most direct way is to simulate every possible path from the start cell. At each position, you follow the allowed movement determined by the mirror orientation in that cell. A recursive DFS explores both possible directions whenever the mirror allows branching. This approach is useful for understanding how the mirror redirection affects movement across the matrix. However, many subproblems repeat because different paths often reach the same cell with identical conditions.

Approach 2: DFS with Memoization (Dynamic Programming) (O(m*n) time, O(m*n) space)

Instead of recomputing the number of ways from the same cell repeatedly, store results in a memo table. When DFS reaches a cell (i, j), compute the number of valid paths from that state once and cache it. If the same state appears again, return the stored value immediately. This converts the exponential recursion into a linear number of states equal to the number of cells. The idea mirrors classic grid path counting but adjusts transitions depending on the mirror orientation stored in the grid. Memoization works well here because the number of unique states in the dynamic programming formulation is bounded by m * n.

Approach 3: Bottom-Up DP on the Grid (O(m*n) time, O(m*n) space)

A tabulation approach builds the solution iteratively. Create a DP table where dp[i][j] represents the number of ways to reach cell (i, j). Initialize the start cell with 1. Then iterate through the grid row by row. For each cell, propagate its path count to the next cell(s) determined by the mirror orientation. For example, a mirror may redirect the path to the right neighbor or the cell below. This avoids recursion and gives predictable performance. Since the grid structure is fixed, each state contributes to at most two transitions, making the total work proportional to the number of cells.

Approach 4: Space Optimized DP (O(m*n) time, O(n) space)

If transitions only depend on the current row and the next row, the DP table can be compressed into a rolling array. Instead of storing the entire m x n table, maintain only the current row and update values while iterating through the grid. This technique is common in array-based grid DP problems where dependencies are limited to adjacent cells.

Recommended for interviews: The bottom-up dynamic programming approach is usually what interviewers expect. A brute force DFS demonstrates that you understand the path rules and mirror behavior, but the DP optimization shows you recognize overlapping subproblems and can reduce the complexity to O(m*n).

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force DFSO(2^(m+n))O(m+n)Understanding path rules and mirror behavior for small grids
DFS + MemoizationO(m*n)O(m*n)General solution when recursion is easier to implement
Bottom-Up Dynamic ProgrammingO(m*n)O(m*n)Interview-friendly approach with deterministic iteration
Space Optimized DPO(m*n)O(n)Large grids where reducing memory usage matters

Video Solution

Twisted Mirror Path Count | LeetCode 3665 | Biweekly Contest • Sanyam IIT Guwahati • 353 views views

Watch 6 more video solutions →

Frequently Asked Questions

Is Twisted Mirror Path Count easy or hard?
Twisted Mirror Path Count is generally classified as a Medium problem. The main challenge is correctly modeling the mirror direction rules and converting the path traversal into a dynamic programming state transition.
Twisted Mirror Path Count Python/Java solution
The solution typically uses a DP matrix or memoized DFS. Python implementations often use recursion with a dictionary cache or a 2D list DP table, while Java implementations use an integer 2D array and iterative loops to propagate path counts.
How to solve Twisted Mirror Path Count in O(n)?
Use a space-optimized dynamic programming technique. Instead of storing the full m x n DP table, maintain a rolling array representing the current row of path counts. Updates propagate according to the mirror direction, reducing space complexity to O(n) while keeping time complexity O(m*n).
What is the best approach for Twisted Mirror Path Count?
Dynamic programming over the grid is the most efficient solution. Each cell stores the number of ways to reach or leave that position while respecting the mirror direction. This reduces repeated work and runs in O(m*n) time with O(m*n) space.
Is Twisted Mirror Path Count asked at Google/Amazon/Meta?
Grid dynamic programming and path-counting problems appear frequently in interviews at companies like Google, Amazon, and Meta. Variants involving obstacles, direction constraints, or grid transformations are common interview patterns.
What data structure is used in Twisted Mirror Path Count?
The core structure is a 2D dynamic programming array representing the matrix state. Each entry tracks the number of valid ways to reach a cell while following the mirror redirection rules.
What is the time complexity of Twisted Mirror Path Count?
The optimal dynamic programming solution runs in O(m*n) time where m and n are the grid dimensions. Each cell is processed once and contributes to a constant number of transitions based on the mirror orientation.

Ready to solve this problem?

Practice Twisted Mirror Path Count with our built-in code editor and test cases.

Practice on FleetCode