FastPrepMinimum Distance to Return a Book

Minimum Distance to Return a Book

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

You are given a rectangular map grid, a starting coordinate start, and the direct train distance from every train station to its closest library.

Each cell in grid is one of:

  • ., an open cell;
  • #, a blocked cell;
  • L, a library; or
  • T, a train station.

You may walk one cell up, down, left, or right at a cost of 1, staying inside the map and never entering a blocked cell. Libraries and train stations are walkable.

The values in stationToLibrary correspond to the T cells in row-major order. Reaching a train station lets you immediately finish the trip at that station's closest library for the corresponding additional train distance.

Return the minimum total distance needed to return the book. A valid trip either walks directly onto a library or walks to a train station and then uses its direct connection. Return -1 when neither option is reachable.

Function

minimumLibraryReturnDistance(grid: String[], start: int[], stationToLibrary: int[]) → int

Examples

Example 1

grid = ["...L",".##.","T..."]start = [0,0]stationToLibrary = [2]return = 3

Walking right three times reaches the library at [0,3]. Walking two steps to the station and then traveling distance 2 would cost 4.

Example 2

grid = ["L###","###T","...."]start = [2,0]stationToLibrary = [2]return = 6

The library cannot be reached by walking. The station at [1,3] is four walking steps away, and its direct train distance is 2.

Example 3

grid = ["L#T","###","..."]start = [2,1]stationToLibrary = [3]return = -1

The blocked middle row separates the start from both the library and the train station.

Constraints

  • 1 <= grid.length and 1 <= grid[row].length.
  • All rows have the same length, and the map contains at most 200000 cells.
  • Every cell is one of ., #, L, or T.
  • The map contains at least one library.
  • start is an in-bounds coordinate whose cell is not blocked.
  • stationToLibrary.length equals the number of train stations.
  • 0 <= stationToLibrary[i] <= 10^9.

More Google problems

See Google hiring insights
public int minimumLibraryReturnDistance(String[] grid, int[] start, int[] stationToLibrary) {
  // Write your code here.
}
grid["...L",".##.","T..."]
start[0,0]
stationToLibrary[2]
expected3
Checking account…