Find shortest distance in grid
Last updated: May 20, 2026
Quick Overview
Given a 2D grid consisting of 0s and 1s, where 0 represents an empty cell and 1 represents an obstacle, write a function to find the shortest distance from a starting point to a target point, moving only through the empty cells. The function should return the length of the shortest path, or -1 if no path exists. The input will be the grid as a list of lists, and the starting and target points as tuples of coordinates.
Elastic
May 20, 2026455
2
609 solved
Given a 2D grid consisting of 0s and 1s, where 0 represents an empty cell and 1 represents an obstacle, write a function to find the shortest distance from a starting point to a target point, moving only through the empty cells. The function should return the length of the shortest path, or -1 if no path exists. The input will be the grid as a list of lists, and the starting and target points as tuples of coordinates.
This coding problem is frequently asked during Onsite at Elastic. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Elastic expects candidates to write production-quality code, not just solve the puzzle.
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)?
- Can you solve this in a single pass?
- How would your solution change if the input was sorted?
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
This problem can be classified under the Breadth-First Search (BFS) pattern, which is ideal for finding the shortest path in an unweighted grid. BFS explores all possible paths layer by layer, making ...
Approach
- Initialization: Start by checking if the starting or target points are out of bounds or if they are obstacles (1). If so, return -1.
- Setup BFS: Initialize a queue to keep track of the ...