Search and Shortest-Path Algorithms
Trees & GraphsModel answerLast updated
Implement binary search on a monotone predicate, BFS for state-space and grid shortest paths, and random board generation with adjacency counting.
You will solve four independent algorithmic problems that test search and traversal techniques:
Problem 1: Find Maximum Valid Floor
You have access to a function canOperate(floor) that returns true if floor number floor is valid for operation, and false otherwise. Floors are numbered 1 through n. There exists a threshold floor T such that all floors numbered <= T return true and all floors > T return false. Find T using at most O(log n) calls to canOperate.
Input: An integer n (the total number of floors) and access to the canOperate function.
Output: The highest floor number that returns true, or 0 if no floor is valid.
Problem 2: Minimum Moves for Combination Lock
A lock consists of four wheels, each displaying a digit from 0 to 9. On each move, you can rotate one wheel up or down by exactly one digit, with wraparound (9 + 1 = 0, 0 - 1 = 9). Some combinations are forbidden and cannot be visited during the unlocking process.
Given a starting combination, a target combination, and a set of forbidden combinations, determine the minimum number of moves required to reach the target from the start without passing through any forbidden state. If it is impossible, return -1.
Input: Strings start and target (each four digits), and a set forbidden of four-digit strings.
Output: Minimum number of moves, or -1 if unreachable.
Problem 3: Shortest Distance to Grid Boundary
You are given a rectangular grid where each cell is either open (.) or a wall (+). You start at a given open cell inside the grid. In each step, you may move to an adjacent open cell (up, down, left, or right). Find the minimum number of steps to reach any open cell on the boundary of the grid, excluding the starting cell itself. If no such exit exists, return -1.
Input: A 2D grid of characters and a starting position (row, col).
Output: Minimum steps to an open boundary cell, or -1 if impossible.
Problem 4: Random Mine Placement with Counts
Generate a minesweeper board of size rows × cols with exactly N mines placed uniformly at random in distinct cells. Each non-mine cell should contain the count of mines in its eight neighboring cells (or fewer for edge and corner cells). Use -1 to represent a mine.
Input: Integers rows, cols, and N (number of mines).
Output: A 2D list of integers representing the board.
Constraints: 0 <= N <= rows * cols
Hints
Hint 1
For the floor problem, maintain an invariant where one boundary is always valid and the other always invalid.
Hint 2
BFS explores nodes in order of increasing distance; use it when all edges have equal weight.
Hint 3
Mark cells or states as visited when you enqueue them, not when you dequeue, to avoid duplicate work.
Hint 4
Use random.sample to pick N distinct cells uniformly without replacement; avoid retry loops that degrade as density increases.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
These problems assess your ability to recognize when to apply binary search, breadth-first search on implicit graphs, grid traversal, and clean randomized generation.
Problem 1: Find Maximum Valid Floor
Approach:
The function canOperate exhibits a monotone property: it returns true for all floors up to some threshold T, then false for all floors beyond T. This is a perfect fit for binary search. Maintain two pointers lo and hi such that lo is always a valid floor and hi + 1 is always invalid. Start with lo = 0 (a sentinel representing "no valid floor") and hi = n. At each step, compute mid = (lo + hi + 1) // 2 (rounding up to ensure progress), query canOperate(mid), and update the bounds accordingly. When lo == hi, you have found T.
Why round up:
Using (lo + hi + 1) // 2 ensures mid > lo when lo < hi, preventing infinite loops in the two-element case.
Complexity:
Time O(log n) calls to canOperate, space O(1).
Code:
def find_max_valid_floor(n: int, canOperate) -> int:
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2
if canOperate(mid):
lo = mid
else:
hi = mid - 1
return lo
Problem 2: Minimum Moves for Combination Lock
Approach:
Model the problem as a graph where each four-digit state is a node, and two nodes are connected if they differ by exactly one wheel rotation. Each node has exactly 8 neighbors (4 wheels × 2 directions). Since all edges have unit cost, breadth-first search finds the shortest path from start to target. Treat forbidden states as walls by adding them to the visited set initially.
Key implementation details:
- Check if
startortargetis forbidden before beginning. - If
start == target, return0. - Mark states visited when enqueueing to prevent duplicates in the queue.
- For each neighbor, if it equals the target, return immediately with
dist + 1.
Complexity:
The state space has 10^4 nodes and 8 × 10^4 edges. Time is O(10^4) with a small constant for string operations. Space is O(10^4) for the visited set and queue.
Code:
from collections import deque
def min_lock_moves(start: str, target: str, forbidden: set[str]) -> int:
if start in forbidden or target in forbidden:
return -1
if start == target:
return 0
visited = set(forbidden)
visited.add(start)
queue = deque([(start, 0)])
while queue:
state, dist = queue.popleft()
for i in range(4):
digit = int(state[i])
for delta in (1, -1):
new_digit = (digit + delta) % 10
neighbor = state[:i] + str(new_digit) + state[i+1:]
if neighbor == target:
return dist + 1
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, dist + 1))
return -1
Problem 3: Shortest Distance to Grid Boundary
Approach:
Run BFS starting from the given cell. Explore all reachable open cells, and the first time you discover an open boundary cell (other than the start itself), return the distance. A cell is on the boundary if its row is 0 or rows - 1, or its column is 0 or cols - 1.
Key implementation details:
- Mark the start as visited before beginning the search so it is never rediscovered.
- Check the boundary condition when a neighbor is first discovered, not when it is dequeued.
- Use a 2D visited array to track explored cells.
Complexity:
Time O(rows × cols) since each cell is visited at most once. Space O(rows × cols) for the visited array and queue.
Code:
from collections import deque
def shortest_exit_distance(grid: list[list[str]], start: tuple[int, int]) -> int:
rows, cols = len(grid), len(grid[0])
sr, sc = start
visited = [[False] * cols for _ in range(rows)]
visited[sr][sc] = True
queue = deque([(sr, sc, 0)])
while queue:
r, c, dist = queue.popleft()
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc] and grid[nr][nc] == '.':
if nr == 0 or nr == rows - 1 or nc == 0 or nc == cols - 1:
return dist + 1
visited[nr][nc] = True
queue.append((nr, nc, dist + 1))
return -1
Problem 4: Random Mine Placement with Counts
Approach:
Break the problem into two steps:
-
Place mines uniformly:
Flatten the grid conceptually into indices0throughrows*cols - 1. Userandom.sample(range(rows*cols), N)to selectNdistinct indices uniformly at random. Convert each index back to(row, col)using integer division and modulo. -
Compute neighbor counts:
Iterate over every mine cell. For each mine, increment the count in all neighboring non-mine cells. Usemaxandminto clamp neighbor indices within bounds.
Why this is correct:
random.sample implements sampling without replacement, guaranteeing uniform distribution over all N-subsets. Each non-mine cell is incremented exactly once per adjacent mine, so its final value is the correct count.
Complexity:
Time O(rows × cols): sampling is O(N), and counting is O(8N). Space O(rows × cols) for the board.
Code:
import random
MINE = -1
def generate_minesweeper(rows: int, cols: int, N: int) -> list[list[int]]:
if not (0 <= N <= rows * cols):
raise ValueError("Invalid mine count")
board = [[0] * cols for _ in range(rows)]
# Place mines
for idx in random.sample(range(rows * cols), N):
r, c = divmod(idx, cols)
board[r][c] = MINE
# Compute counts
for r in range(rows):
for c in range(cols):
if board[r][c] == MINE:
for nr in range(max(0, r - 1), min(rows, r + 2)):
for nc in range(max(0, c - 1), min(cols, c + 2)):
if board[nr][nc] != MINE:
board[nr][nc] += 1
return board
Common Mistakes
- Binary search: Using
(lo + hi) // 2without considering rounding direction can cause infinite loops. - BFS: Marking nodes visited only when dequeued leads to duplicate entries and exponential blowup.
- Grid boundary: Forgetting to exclude the starting cell when it is already on the boundary.
- Mine placement: Using a retry loop ("pick a random cell, retry if occupied") degrades to
O(∞)asNapproachesrows*cols.