Solve two grid problems (islands + min-cost path)
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This pair of problems evaluates grid-based algorithm competencies, specifically connected-component detection and translation-invariant shape recognition for distinct-island counting, plus shortest-path/graph-search reasoning under unit-change costs for the directed-grid minimum-cost path.
Part 1: Count Distinct Translation-Equivalent Islands
Constraints
- 1 <= len(grid) <= 500
- 1 <= len(grid[0]) <= 500
- grid[i][j] is either 0 or 1
- The grid is rectangular
- Aim for O(m * n) time
Examples
Input: ([[0]],)
Expected Output: 0
Explanation: There is no land, so there are no island shapes.
Input: ([[1]],)
Expected Output: 1
Explanation: There is exactly one island consisting of one cell.
Input: ([[1, 1, 0, 0, 0], [1, 0, 0, 1, 1], [0, 0, 0, 1, 0], [1, 1, 0, 0, 0], [1, 0, 0, 1, 1]],)
Expected Output: 2
Explanation: There are multiple L-shaped islands with the same translation-normalized shape, plus one horizontal domino shape.
Input: ([[1, 1, 0, 1, 1], [1, 0, 0, 0, 1]],)
Expected Output: 2
Explanation: The two islands are mirror images, but reflections do not count as the same shape.
Input: ([[1, 0, 1], [0, 1, 0], [1, 0, 1]],)
Expected Output: 1
Explanation: Diagonal land cells are not connected, so there are five single-cell islands, all with the same shape.
Hints
- For each island, record every land cell relative to the island's first discovered cell.
- Store a canonical representation of each normalized island shape in a set.
Part 2: Minimum Cost to Create a Valid Path in a Directed Grid
Constraints
- 1 <= len(dir) <= 1000
- 1 <= len(dir[0]) <= 1000
- dir[i][j] is one of 1, 2, 3, or 4
- The grid is rectangular
- Aim for near-linear time in the number of cells
Examples
Input: ([[1]],)
Expected Output: 0
Explanation: The start cell is already the destination.
Input: ([[1, 1, 3], [3, 2, 2], [1, 1, 4]],)
Expected Output: 0
Explanation: Following the existing directions already reaches the bottom-right cell.
Input: ([[1, 2], [4, 3]],)
Expected Output: 1
Explanation: Follow right from the start, then change the top-right cell to point down.
Input: ([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]],)
Expected Output: 3
Explanation: At least three downward moves are needed, and each downward move requires changing a cell's direction.
Input: ([[4, 4, 4], [4, 4, 4], [4, 4, 4]],)
Expected Output: 4
Explanation: All arrows point upward, so every right or down move on a shortest path requires a direction change.
Hints
- Model each cell as a graph node. Moving in the cell's current direction has cost 0; moving in any other valid direction has cost 1.
- Because all edge weights are only 0 or 1, use 0-1 BFS with a deque instead of ordinary BFS.