Multi-Part Algorithm Challenge: Grids, Medians, and Traversals
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests implementation of connected-component search in grids, efficient median computation across sorted sequences, and breadth-first and depth-first graph traversals.
You are given four inputs and must return a dictionary containing five results from three independent algorithmic tasks.
Task 1: Largest Island in a Binary Grid
Given an m × n grid containing only 0s and 1s, find the size of the largest island. An island is a maximal group of 1s connected through 4-directional adjacency (up, down, left, right). Diagonal connections do not count.
Return the count of cells in the largest island, or 0 if no island exists.
Task 2: Median Across Two Sorted Arrays
Given two sorted arrays a and b (each in non-decreasing order), compute the median of all elements combined as if they were merged into one sorted sequence.
- If the total number of elements is odd, return the middle element as its original type (int remains int).
- If the total number of elements is even, return the average of the two middle elements as a float.
- If both arrays are empty, return
None.
Task 3: Graph Traversals (BFS and DFS)
Given an undirected graph represented as an adjacency list graph where graph[i] is the list of neighbors of vertex i, return the visitation order for:
- Breadth-first search (BFS): Process vertices level by level.
- Depth-first search (DFS), recursive: Explore as deeply as possible before backtracking.
- Depth-first search (DFS), iterative: Use an explicit stack to replicate depth-first exploration.
The graph may be disconnected. Start from vertex 0, then 1, then 2, and so on, visiting each unvisited vertex in numerical order. Within each vertex, explore neighbors in the order they appear in the adjacency list.
For the iterative DFS, mark vertices as visited when they are pushed onto the stack (not when popped).
Output Format
Return a dictionary with these exact keys:
{
'largest_component': int,
'median': int | float | None,
'bfs': List[int],
'dfs_recursive': List[int],
'dfs_iterative': List[int]
}
Constraints
0 ≤ m, n ≤ 1000(grid dimensions)0 ≤ len(a), len(b) ≤ 10^50 ≤ len(graph) ≤ 1000(number of vertices)- Each adjacency list may contain duplicates or self-loops
- All array elements fit in a 32-bit signed integer
Examples
Example 1
Input: algorithm_suite([[1, 1, 0], [0, 1, 0], [1, 0, 1]], [1, 3], [2], [])
Output: {'largest_component': 3, 'median': 2, 'bfs': [], 'dfs_recursive': [], 'dfs_iterative': []}
Example 2
Input: algorithm_suite([[0, 0], [0, 0]], [1, 2], [3, 4], [[1], [0, 3], [3], [1, 2]])
Output: {'largest_component': 0, 'median': 2.5, 'bfs': [0, 1, 3, 2], 'dfs_recursive': [0, 1, 3, 2], 'dfs_iterative': [0, 1, 3, 2]}
Example 3
Input: algorithm_suite([[1, 1, 1], [1, 1, 1]], [1], [2], [])
Output: {'largest_component': 6, 'median': 1.5, 'bfs': [], 'dfs_recursive': [], 'dfs_iterative': []}
Hints
Hint 1
For the grid, use flood-fill from each unvisited cell containing a 1. Mark cells as visited immediately when discovered to avoid revisiting them.
Hint 2
For the median, avoid merging the arrays. Binary search over a partition point: choose how many elements to take from each array so the left half contains exactly ⌈(m+n)/2⌉ elements and every left element is ≤ every right element.
Hint 3
For graph traversals, use an outer loop over all vertices to handle disconnected components. In iterative DFS, push neighbors in reverse order so the first neighbor is processed first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem bundles three classic algorithmic tasks. Each can be solved independently.
Task 1: Largest Island
Scan the grid row by row. Whenever you encounter a 1 that hasn't been visited, perform a flood-fill to explore its entire island. Use an explicit stack (iterative DFS) to avoid recursion depth issues on large grids. Mark each cell as visited the moment you add it to the stack, ensuring each cell is processed exactly once. Track the size of each island and keep the maximum.
Why it works: Flood-fill from a cell explores exactly the cells reachable through 4-directional steps over 1s. Sharing the seen matrix across all start points ensures each island is counted once.
Task 2: Median Without Merging
Merging both arrays takes O(m + n) time. Instead, use binary search over a partition. Swap the arrays so that a is the shorter one. Search for an index i in a such that when you take i elements from a and j = half - i elements from b (where half = ⌈(m+n)/2⌉), every element on the left is ≤ every element on the right. This condition becomes:
a[i-1] ≤ b[j] and b[j-1] ≤ a[i]
Use -∞ and +∞ sentinels when i or j is at a boundary. Once you find the valid partition:
- If the total count is odd, return
max(a[i-1], b[j-1]). - If even, return the average of the left maximum and the right minimum.
Why it works: A valid partition places exactly half elements on the left, all smaller than or equal to the right elements. Binary search over i is efficient because the partition condition is monotonic in i.
Task 3: Graph Traversals
All three traversals use an outer loop over vertices 0, 1, 2, ... to handle disconnected components.
- BFS: Use a queue (simulated with a list and a head index). Mark each vertex visited when you enqueue it, and record it when you dequeue.
- Recursive DFS: Mark the vertex, record it, then recurse on unvisited neighbors in list order. This is a standard preorder traversal.
- Iterative DFS: Use an explicit stack. Push neighbors in reverse order so the first neighbor is popped first. Mark vertices visited when pushed (not popped) to prevent duplicate stack entries.
Note: Iterative DFS with mark-on-push does not always produce the same order as recursive DFS when there are multiple paths to a vertex, but both are valid depth-first orders.
Complexity
-
Task 1 (Largest island):
Time: O(m·n). Each cell is visited once.
Space: O(m·n) for theseenmatrix and stack. -
Task 2 (Median):
Time: O(log min(m, n)). Binary search over the shorter array.
Space: O(1). -
Task 3 (Graph traversals):
Time: O(V + E) for each traversal. Every vertex and edge is processed once.
Space: O(V) for the visited array, queue/stack, and recursion stack (recursive DFS).
Solution
from typing import Dict, List
def algorithm_suite(grid, a, b, graph):
# Task 1: Largest island via flood-fill
rows = len(grid)
cols = len(grid[0]) if rows else 0
seen = [[False] * cols for _ in range(rows)]
largest = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
seen[r][c] = True
stack = [(r, c)]
size = 0
while stack:
x, y = stack.pop()
size += 1
for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1 and not seen[nx][ny]:
seen[nx][ny] = True
stack.append((nx, ny))
largest = max(largest, size)
# Task 2: Median via binary search on partition
if len(a) > len(b):
a, b = b, a
m, n = len(a), len(b)
if m + n == 0:
median = None
else:
lo, hi = 0, m
half = (m + n + 1) // 2
while lo <= hi:
i = (lo + hi) // 2
j = half - i
left_a = float('-inf') if i == 0 else a[i - 1]
right_a = float('inf') if i == m else a[i]
left_b = float('-inf') if j == 0 else b[j - 1]
right_b = float('inf') if j == n else b[j]
if left_a <= right_b and left_b <= right_a:
left_max = max(left_a, left_b)
if (m + n) % 2:
median = left_max
else:
median = (left_max + min(right_a, right_b)) / 2.0
break
if left_a > right_b:
hi = i - 1
else:
lo = i + 1
# Task 3: Graph traversals
count = len(graph)
visited = [False] * count
bfs_order = []
for start in range(count):
if visited[start]:
continue
visited[start] = True
queue = [start]
head = 0
while head < len(queue):
node = queue[head]
head += 1
bfs_order.append(node)
for neighbor in graph[node]:
if not visited[neighbor]:
visited[neighbor] = True
queue.append(neighbor)
recursive_order = []
visited = [False] * count
def visit(node):
visited[node] = True
recursive_order.append(node)
for neighbor in graph[node]:
if not visited[neighbor]:
visit(neighbor)
for start in range(count):
if not visited[start]:
visit(start)
iterative_order = []
visited = [False] * count
for start in range(count):
if visited[start]:
continue
visited[start] = True
stack = [start]
while stack:
node = stack.pop()
iterative_order.append(node)
for neighbor in reversed(graph[node]):
if not visited[neighbor]:
visited[neighbor] = True
stack.append(neighbor)
return {
'largest_component': largest,
'median': median,
'bfs': bfs_order,
'dfs_recursive': recursive_order,
'dfs_iterative': iterative_order,
}