BFS on array
Last updated: February 27, 2026
Quick Overview
Given a 2D array representing a grid, implement a Breadth-First Search (BFS) algorithm to find the shortest path from a starting position to a target position. The grid can contain obstacles that cannot be traversed, and you should return the length of the shortest path or -1 if no path exists. The input will be the grid as an array of arrays, and the output should be an integer representing the path length.
Twilio
February 27, 2026473
13
1,660 solved
Given a 2D array representing a grid, implement a Breadth-First Search (BFS) algorithm to find the shortest path from a starting position to a target position. The grid can contain obstacles that cannot be traversed, and you should return the length of the shortest path or -1 if no path exists. The input will be the grid as an array of arrays, and the output should be an integer representing the path length.
This coding problem is frequently asked during Phone Screen at Twilio. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Twilio expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
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 is the worst-case input for your solution?
- 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
This problem involves finding the shortest path in a grid using Breadth-First Search (BFS). BFS is suitable here because it explores all possible paths level by level, ensuring that we find the shorte...
Approach
- Initialize BFS: Start by creating a queue to hold the current position (starting point) and a variable to track the path length.
- Mark Visited Cells: Use a set to track visited cells to p...