TikTok Round 1
Anonymous User
23886

I got asked the following question during my TikTok first round. Despite being very comfortable with Graphs and DFS, had a massive brain fart and forgot to mark the nodes as visited. Time was short for me because I thought the interview was 1 hour long but it was 45 minutes. Literally, got the code working 3 minutes after the interview ended. Hoping y'all can avoid the said brain fart!

We have a m x n 2D grid initialized with three possible values:
-1 - An obstacle.
0 - An exit.
INF - An empty room. We use the value 2^31 - 1 = 2147483647 to represent INF as you may assume that the distance to an exit is less than 2147483647.

We want to fill each empty room with the distance to its nearest exit. If it is impossible to reach an exit, it should be filled with INF.

Example:
Given the 2D grid:

INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF

We expect the output 2D grid as:

3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4


 public static void shortestPathToExit(int[][] grid) {
   if (grid == null || grid.length == 0) {
       return;
   }
   
   for (int i = 0; i < grid.length; i++) {
       for (int j = 0; j < grid[0].length; j++) {
           if (grid[i][j] == 0) {
               dfs(grid, i, j, 0);
           }
       }
   }
}

public static void dfs(int[][] grid, int i, int j, int distance) {
   
   if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == -1 || (grid[i][j] == 0 && distance > 0)) {
       return;
   }
   
   grid[i][j] = Math.min(grid[i][j], distance);
   System.out.println("i: " + i + ", j: "+ j + " ,dist: " + distance);
   dfs(grid, i + 1, j, distance + 1);
   dfs(grid, i - 1, j, distance + 1);
   dfs(grid, i, j + 1, distance + 1);
   dfs(grid, i, j - 1, distance + 1);
   
}

EDIT: This was for Software Engineer in Mountain View, CA.

Comments (12)