Solve grid shortest-path and tree DP
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question pair evaluates proficiency in fundamental algorithmic techniques: finding shortest paths in a grid via breadth-first search and applying dynamic programming on trees to maximize a sum under adjacency constraints, assessing graph traversal, state management, optimal substructure recognition, and complexity handling.
Part 1: Shortest Path in a Maze
Constraints
- 1 <= number of rows, columns <= 2000
- All rows in `grid` have the same length
- `start` and `end` are within bounds
- Moves are allowed only in 4 directions: up, down, left, right
- For valid inputs, `start` and `end` are on open cells
Examples
Input: (['...', '.#.', '...'], (0, 0), (2, 2))
Expected Output: 4
Explanation: The wall in the center blocks the direct route, so the shortest path goes around it in 4 steps.
Input: (['.#', '##', '..'], (0, 0), (2, 1))
Expected Output: -1
Explanation: The start cell has no reachable open neighbors, so the end cannot be reached.
Input: (['.'], (0, 0), (0, 0))
Expected Output: 0
Explanation: Edge case: start and end are the same cell.
Input: (['..#..', '#.#.#', '#...#', '###.#', '.....'], (0, 0), (4, 4))
Expected Output: 8
Explanation: A narrow valid route exists through the middle and lower rows; the shortest path length is 8.
Hints
- Because every move costs the same amount, breadth-first search explores cells in increasing distance order.
- Mark cells as visited as soon as you add them to the queue, so you never process the same cell twice.
Part 2: Maximum Sum of Non-Adjacent Tree Nodes
Constraints
- 0 <= number of nodes <= 100000
- 0 <= node values <= 10000
- The tree is represented in level-order with `None` for missing children
- You should aim for an O(n) solution
Examples
Input: [3, 2, 3, None, 3, None, 1]
Expected Output: 7
Explanation: Choose the root (3), the left-right grandchild (3), and the right-right grandchild (1). Total = 7.
Input: [3, 4, 5, 1, 3, None, 1]
Expected Output: 9
Explanation: The optimal choice is 4 + 5 = 9. Taking the root would lead to a smaller total.
Input: []
Expected Output: 0
Explanation: Edge case: an empty tree has sum 0.
Input: [10]
Expected Output: 10
Explanation: Edge case: with only one node, the best answer is to take it.
Input: [4, 1, None, 2, None, 3]
Expected Output: 7
Explanation: The best selection is 4 and 3, which are not direct parent and child.
Hints
- For each node, track two answers: the best sum if you take this node, and the best sum if you skip it.
- A postorder traversal is useful because a parent's answer depends on results already computed for its children.