FastPrepNearest Charging Station on a Grid

Nearest Charging Station on a Grid

Spotify logoSpotify● MediumFULLTIMEONSITE INTERVIEW

Problem statement

You are given a grid as an array of strings. Each cell is one of:

  • C: a charging station
  • V: an electric vehicle
  • .: an empty cell

A vehicle moves one cell at a time, up, down, left or right. The grid has no obstacles, so a vehicle can pass through any cell, including other vehicles and charging stations.

For each vehicle, find the fewest moves it needs to reach any charging station. Return these distances in an array, going row by row from the top and left to right within each row. If the grid has no charging station, the distance for every vehicle is -1.

An empty grid or a grid with no vehicles returns an empty array.

Function

nearestChargerDistances(grid: String[]) → int[]

Examples

Example 1

grid = ["V.C","...","C.V"]return = [2,2]

The vehicle at row 0, column 0 is two moves from the station at row 0, column 2. The vehicle at row 2, column 2 is two moves from the station at row 0, column 2. The answer lists them in row order: [2,2].

Example 2

grid = ["C...V"]return = [4]

The only vehicle is at column 4 and the only station is at column 0, so it needs 4 moves.

Example 3

grid = ["V.V"]return = [-1,-1]

There is no charging station, so both vehicles get -1.

Example 4

grid = ["...","C.C"]return = []

There is no vehicle, so the answer is an empty array.

Constraints

  • 0 <= grid.length <= 100
  • 1 <= grid[i].length <= 100
  • All rows have the same length.
  • Every character of grid[i] is C, V or .

More Spotify problems

See Spotify hiring insights
Saved
public int[] nearestChargerDistances(String[] grid) {
    // Write your code here.
}
Checking account…