Fewest Sign Flips So a Grid of Arrows Leads to the Exit
Last updated: November 29, 2026
Quick Overview
Each cell of an m x n grid holds an arrow pointing right, left, down or up (1 to 4); following the arrow is free, and changing a cell's arrow costs 1. Return the minimum total cost so that following arrows from the top-left reaches the bottom-right.
0
0
0 solved
Each cell of an m x n grid holds an arrow pointing right, left, down or up (1 to 4); following the arrow is free, and changing a cell's arrow costs 1. Return the minimum total cost so that following arrows from the top-left reaches the bottom-right.
A Google onsite Hard problem that hinges on recognizing a 0-1 weighted shortest path. The interviewer wants to see the reduction to edge weights 0 and 1 and the deque-based 0-1 BFS rather than full Dijkstra, with a correct argument for optimality.
What the Interviewer Expects
- Models each cell as a node with four edges, cost 0 for the arrow's direction and 1 otherwise
- Argues that changing a cell twice is never useful
- Implements 0-1 BFS with a deque
- Skips stale deque entries
- States O(mn) time
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Changing an arrow costs different amounts per cell; what algorithm now?
- Return which cells to change.
- Some cells are walls that cannot be entered or changed.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
grid[r][c]in {1: right, 2: left, 3: down, 4: up}.- Moving in the arrow's direction costs 0; any other direction costs 1 (we pay to repoint the cell).
- Output: minimum cost from
(0,0)to `(m-1...
High-Level Design
Changing a cell's arrow lets you leave it in any direction, and a shortest path visits each cell at most once, so paying 1 for an off-arrow move is exact. All edges cost 0 or 1, which allows 0-1 BFS: ...