Optimize flight costs and find grid path
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithm design and problem-solving skills for array-based cost optimization and grid pathfinding, including selection under ordering constraints, path existence detection and path reconstruction, together with correctness and edge-case reasoning.
Optimize Flight Costs (Depart Then Return)
Constraints
- 1 <= n <= 10^5 (length of D equals length of R)
- Costs may be any 32-bit integers, including negatives
- Return must be strictly after departure: i < j
- If n < 2 there is no valid (i, j) pair; return [-1, -1, -1]
- On ties, the earliest return day j (and the cheapest departure index recorded before it) is reported
Examples
Input: ([5, 2, 8, 1], [10, 3, 6, 4])
Expected Output: [6, 1, 3]
Explanation: Cheapest departure before day 3 is day 1 (cost 2). Combined with return cost R[3]=4 gives total 6, the minimum.
Input: ([1], [1])
Expected Output: [-1, -1, -1]
Explanation: n = 1 < 2, so no valid (i, j) with i < j exists.
Hints
- You do not need to try all O(n^2) pairs. Fix the return day j and ask: what is the cheapest departure on any day before j?
- Scan left to right keeping `minDepCost` and its index among days 0..j-1. At day j, the best total ending here is minDepCost + R[j].
- Update the running best total before updating minDepCost with D[j], so day j is never used as its own departure-and-return.
- Handle n < 2 up front by returning [-1, -1, -1].
Find a Path Through a Binary Grid
Constraints
- 1 <= m, n (the grid has at least one cell)
- Each cell is 0 (walkable) or 1 (blocked)
- Moves are 4-directional: up, down, left, right; no diagonals
- Start (0,0) and destination (m-1,n-1) may themselves be blocked, in which case return []
- When a path exists, BFS returns a shortest path; with neighbor order down, right, up, left the path is deterministic
Examples
Input: ([[0, 0, 0], [0, 1, 0], [0, 0, 0]],)
Expected Output: [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2]]
Explanation: The center cell (1,1) is blocked, so BFS routes down the left column then across the bottom row to reach (2,2).
Input: ([[0, 1], [1, 0]],)
Expected Output: []
Explanation: From (0,0) both the right cell (0,1) and the down cell (1,0) are blocked, so the destination is unreachable.
Hints
- Both BFS and DFS work. BFS additionally gives you a shortest path and avoids deep recursion on large grids.
- Mark a cell visited at the moment you enqueue it (not when you dequeue it) to avoid enqueuing the same cell twice.
- Store a parent pointer for every cell when you first discover it, then rebuild the path by following parents from the destination back to the start and reversing.
- Check the start and destination cells for being blocked before searching, and handle the 1x1 grid as its own answer.