Solve Grid Path and Graph Sampling
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
This interview note described two coding problems:
1. **Grid path with shortest time and lowest cost**
You are given an `m x n` grid containing a start cell `S`, an end cell `E`, blocked cells, and open cells. You may move up, down, left, or right to adjacent open cells. Each move takes exactly 1 unit of time. Some cells also have a non-negative fee that is paid when you enter that cell. Find a path from `S` to `E` that minimizes total travel time; among all shortest-time paths, choose one with the minimum total fee. Return the minimum time and minimum fee, or report that no path exists.
2. **Uniformly sample edges that connect multiple components**
You are given `n` disjoint connected undirected graphs `G1, G2, ..., Gn`. You may add edges only between vertices belonging to different graphs, and any such cross-graph edge is allowed. Write a function that returns a random set of exactly `n - 1` new edges such that, after adding them, the union of all `n` graphs becomes connected. The returned edge set must be sampled **uniformly** from the set of all valid connecting edge sets of size `n - 1`.
Quick Answer: This question evaluates graph algorithms and probabilistic/combinatorial reasoning, covering multi-criteria shortest-path optimization (minimizing travel time with a secondary fee objective) and uniform random sampling of edge sets that connect disjoint components.
Part 1: Shortest-Time Grid Path with Minimum Fee
You are given a rectangular grid and a fee matrix of the same size. Each grid cell is one of 'S', 'E', '.', or '#'. 'S' is the start, 'E' is the end, '.' is an open cell, and '#' is blocked. You may move up, down, left, or right to adjacent non-blocked cells. Every move costs 1 unit of time. When you enter a cell, you pay that cell's fee; the starting cell's fee is not paid because you begin there. Find a path from 'S' to 'E' that minimizes total travel time. If several paths have the same minimum travel time, choose the one with the smallest total fee. Return the pair (minimum_time, minimum_fee), or None if no path exists.
Constraints
- 1 <= number of rows, number of columns <= 200
- grid contains exactly one 'S' and exactly one 'E'
- fees[r][c] is a non-negative integer
- You may move only in 4 directions: up, down, left, right
- Blocked cells are marked with '#'; their fee values, if present, are ignored
Examples
Input: (["S..", "..E"], [[0, 5, 1], [1, 1, 2]])
Expected Output: (3, 4)