Find shortest distance in grid
Last updated: April 28, 2026
Quick Overview
Given a 2D grid of cells where each cell represents a point in a coordinate system, find the shortest distance from a starting cell to a target cell while only being able to move up, down, left, or right. The grid may contain obstacles that cannot be traversed, and you should return the minimum number of steps required to reach the target cell, or -1 if it is not reachable.
Apple
April 28, 20263
0
1,112 solved
Given a 2D grid of cells where each cell represents a point in a coordinate system, find the shortest distance from a starting cell to a target cell while only being able to move up, down, left, or right. The grid may contain obstacles that cannot be traversed, and you should return the minimum number of steps required to reach the target cell, or -1 if it is not reachable.
Coding interviews at Apple focus on problem-solving approach as much as the final solution. The interviewer wants to see you break down the problem, consider edge cases, and optimize iteratively. Communication throughout the process is key.
What the Interviewer Expects
- Recognize the underlying problem pattern (sliding window, two pointers, BFS/DFS, etc.)
- Discuss multiple approaches and trade-offs before coding
- Implement an optimal solution with clean, production-quality code
- Handle all edge cases including boundary conditions and invalid input
- Optimize both time and space complexity with clear justification
- Test your solution systematically with well-chosen examples
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
- What if the input doesn't fit in memory?
- Can you solve this iteratively instead of recursively (or vice versa)?
- How would your solution change if the input was sorted?
- How would you parallelize this solution?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem can be categorized as a graph traversal problem, specifically suitable for the Breadth-First Search (BFS) algorithm. BFS is ideal here because it explores all possible paths layer by layer...
Approach
- Initialization: Start by defining the grid dimensions and identifying the starting and target cells. Initialize a queue to facilitate BFS and a set to track visited cells to prevent cycles.
2....