Google | Onsite | Flow water to cities
Anonymous User
3658

Problem description
You're given a grid where each cell grid[r][c] represent city height, overall country (grid) is surrounded by an ocean. You're also given coordinates of two cities c1 and c2, find out the city with minimum height from where we can shower water such that it can reach to the given two cities.
Water can only flow from a city with height h1 to city with height h2 iff h1 >= h2.

Solution proposed

  • Iterate through each cell of the grid
    • Initiate two depth-first searches starting from current cell passing the target coodinate info
  • To improve this, memoise the DFS function so that each cell is visited at-max 2 times
    • Memoisation can only work if you define separate caches for each given target coorindate

Follow-up
Instead of returning city with minimum height, return city from which water can reach both cities the fastest.

Solution proposed

  • Instead of iterating through each cell, run breadth first search simultaneously expanding from both cities
  • Maintain two visited hashsets and as soon as you find an intersecting coordinate, return it as answer (first cell in BFS = shortest distance from both cities)

Interview Experience Post: https://leetcode.com/discuss/interview-question/2199510/Google-or-L4-or-India-or-June-2022-or-Accepted

Comments (4)