Distance from Every Cell to the Nearest EV Charging Station

Last updated: November 29, 2026

Quick Overview

Given a grid where 1 is a charging station, 0 is an open cell, and -1 is a wall, return a grid of the minimum number of 4-directional steps from each cell to its nearest station (-1 for walls and unreachable cells).

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a grid where 1 is a charging station, 0 is an open cell, and -1 is a wall, return a grid of the minimum number of 4-directional steps from each cell to its nearest station (-1 for walls and unreachable cells).

Framed around a Google Maps feature that shades map tiles by distance to charging, this question checks whether you run one multi-source BFS instead of a BFS per cell. Interviewers often follow up by changing the metric or the grid size.

What the Interviewer Expects
  • Rejects per-cell BFS as O((RC)^2)
  • Seeds the queue with all stations at distance 0
  • Uses a distance grid doubling as a visited set
  • Leaves walls and unreachable cells at -1
  • Explains why BFS order gives shortest distances in an unweighted grid
Key Topics to Cover
BFS
Multi-Source BFS
Grids
Graphs
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Cells have different traversal costs (terrain); what changes?
  • Report, for each cell, which station is nearest.
  • The grid is too large for memory; how would you tile and stitch the computation?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: R by C grid with values 1 (station), 0 (open), -1 (wall).
  • Output: same-shape grid of step counts; stations are 0; walls and cells with no reachable station are -1.
  • Moves: up, down, left, ...
High-Level Design

Add a virtual super source connected to every station; BFS from it is exactly BFS seeded with all stations at distance 0. Initialize dist to -1 everywhere, set stations to 0, and push them. Pop cell...


Submit Your Answer
Markdown supported