Evaluate Grid Path Feasibility and Identify Top K Elements
Trees & GraphsModel answerLast updated
Determine matrix path reachability under obstacle constraints and extract the k most frequent elements from an array.
This assessment consists of two independent algorithmic parts commonly combined in technical screening rounds.
Part A: Grid Path Existence
Given a 2D matrix grid of size $m \times n$ containing values 0 (traversable) and 1 (obstacle), determine whether a valid path exists from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1).
Rules & Constraints:
- You can move in 4 cardinal directions: Up, Down, Left, or Right.
- You cannot enter cells marked as
1or move outside the grid boundaries. - Return
trueif a path exists, andfalseotherwise. - The input matrix may be empty or contain invalid start/end positions.
Part B: Most Frequent K Integers
Given an unsorted array of integers nums and an integer k, return an array containing the k most frequent numbers.
Rules & Constraints:
- The order of elements in the output does not matter.
- If multiple elements tie in frequency, any set of valid top
kelements is accepted. - Explain the performance trade-offs of different selection strategies (e.g., Min-Heap, Sorting, Bucket Sort).
Hints
Hint 1
For Part A, consider why iterative Breadth-First Search (BFS) is preferred over recursive Depth-First Search (DFS) on large grids in production environments.
Hint 2
Ensure cells are marked as visited as soon as they are added to the traversal queue to prevent unnecessary duplicate processing.
Hint 3
For Part B, notice that the maximum possible frequency of any number is bounded by the size of the input array N. How can this property be used to achieve linear time complexity?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Grid Path Reachability
Method Explanation
The grid can be modeled as an unweighted graph where each passable cell (0) is a node, and edges connect orthogonal passable neighbors. The objective is to verify graph reachability from (0, 0) to (m - 1, n - 1).
While both Depth-First Search (DFS) and Breadth-First Search (BFS) solve graph connectivity, iterative BFS using a queue is the standard approach for matrix reachability in interview settings:
- Avoids Stack Overflow: On large grids (e.g., $1000 \times 1000$), recursive DFS can hit call stack limits (e.g., Python's default recursion depth limit of 1000).
- Optimal Path Exploration: BFS explores outward in distance layers, reaching the target naturally.
Visited Management Rule: A cell must be marked as visited immediately upon being pushed to the queue, rather than when it is popped. Marking upon pop allows the same unvisited node to be queued multiple times by different neighbors, inflating queue memory to $O(m \times n)$ duplicates.
Complexity Analysis
- Time Complexity: $\mathcal{O}(m \times n)$ — Every cell is enqueued at most once and processes up to 4 neighbors.
- Space Complexity: $\mathcal{O}(m \times n)$ worst-case memory for the visited structure and queue. (Can be reduced to $\mathcal{O}(1)$ auxiliary space if in-place mutation of the input
gridis permitted by overwriting visited0cells with1).
Code (Python)
from collections import deque
from typing import List
def can_reach_destination(grid: List[List[int]]) -> bool:
if not grid or not grid[0]:
return False
rows, cols = len(grid), len(grid[0])
# Check if start or end is blocked
if grid[0][0] == 1 or grid[rows - 1][cols - 1] == 1:
return False
queue = deque([(0, 0)])
visited = [[False] * cols for _ in range(rows)]
visited[0][0] = True
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while queue:
r, c = queue.popleft()
if r == rows - 1 and c == cols - 1:
return True
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if not visited[nr][nc] and grid[nr][nc] == 0:
visited[nr][nc] = True
queue.append((nr, nc))
return False
Part B: Top-K Frequent Elements
Approach Evaluation & Trade-offs
When retrieving the top $k$ elements by frequency, three main algorithms exist:
| Strategy | Time Complexity | Auxiliary Space | Key Characteristics |
|---|---|---|---|
| Sorting | $\mathcal{O}(N + D \log D)$ | $\mathcal{O}(D)$ | Hash frequency map, then sort unique elements ($D$) by count. Simple, but sub-optimal for large inputs. |
| Min-Heap (Priority Queue) | $\mathcal{O}(N + D \log k)$ | $\mathcal{O}(D + k)$ | Maintain a min-heap of size $k$. Ideal when streaming data or when $k \ll D$. |
| Bucket Sort (Frequency Indexing) | $\mathcal{O}(N)$ | $\mathcal{O}(N)$ | Array of buckets where index = frequency. Optimal time complexity since max frequency $\le N$. |
$N$ = total elements in array, $D$ = number of unique elements.
Bucket Sort Strategy
Since frequency cannot exceed the total element count $N$, we create an array of lists buckets of length $N + 1$, where buckets[f] stores all unique numbers appearing exactly $f$ times. Walking backward from index $N$ down to $1$ guarantees elements are collected in descending order of frequency.
Code (Python)
from collections import Counter
from typing import List
import heapq
def top_k_frequent_bucket(nums: List[int], k: int) -> List[int]:
"""Bucket sort approach: O(N) time and O(N) space."""
if not nums or k <= 0:
return []
counts = Counter(nums)
n = len(nums)
# Frequency buckets: index represents frequency count
buckets: List[List[int]] = [[] for _ in range(n + 1)]
for num, freq in counts.items():
buckets[freq].append(num)
result = []
# Iterate backwards from maximum possible frequency
for freq in range(n, 0, -1):
for num in buckets[freq]:
result.append(num)
if len(result) == k:
return result
return result
def top_k_frequent_heap(nums: List[int], k: int) -> List[int]:
"""Min-Heap approach: O(N + D log k) time, optimal for memory constrained environments."""
if not nums or k <= 0:
return []
counts = Counter(nums)
heap = []
for num, count in counts.items():
heapq.heappush(heap, (count, num))
if len(heap) > k:
heapq.heappop(heap)
return [num for count, num in heap]
Interviewer Nuances & Edge Cases
-
Part A Edge Cases:
- Single cell grid
[[0]](start is destination, should returnTrue). - Single cell grid
[[1]](returnsFalse). - Unreachable target completely walled off by
1s. - Mention in-place grid mutation trade-offs: mutating the input matrix saves space but side-effects caller data and causes concurrency bugs in multi-threaded environments.
- Single cell grid
-
Part B Edge Cases:
- Negative values or zeros: Handled seamlessly by hash maps.
- Ties in frequencies: Validated by problem statement; bucket order or heap order does not require secondary sorting unless requested.
- Streamed input: Explain to the interviewer that Bucket Sort requires knowing $N$ upfront, whereas the Min-Heap approach adapts directly to streaming architectures.