Island Detection and Letter Selection Counting
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests graph traversal for connected components in a binary grid and combinatorial counting with multiset constraints.
You are given two separate tasks to solve:
Task 1: Count Land Regions
You receive an m × n grid where each cell contains either '1' (land) or '0' (water). A land region consists of land cells connected horizontally or vertically (not diagonally). All grid edges are treated as water boundaries.
Return the total number of distinct land regions in the grid.
Task 2: Count Letter Selection Methods
You are given an array of uppercase letter characters. Determine how many distinct ways you can select letters from this array such that the selected letters can be rearranged to spell the word GOOGLE.
- Each array position can be used at most once
- Letters at different indices are distinct choices, even if they contain the same character
- The order in which you select letters does not matter (only which positions you choose)
Your function must return a list [region_count, selection_count] containing the answers to both tasks.
Constraints
0 ≤ m, n ≤ 1000wheremis the number of rows andnis the number of columns- Each grid row has exactly
ncharacters - Grid cells contain only
'0'or'1' 0 ≤ len(letters) ≤ 1000- Each element of
lettersis a single uppercase letter ('A'through'Z')
Examples
Example 1
Input: count_regions_and_selections(['11000', '11000', '00100', '00011'], ['G', 'O', 'O', 'G', 'L', 'E'])
Output: [3, 1]
Example 2
Input: count_regions_and_selections(['11110', '11010', '11000', '00000'], ['G', 'G', 'G', 'O', 'O', 'O', 'O', 'L', 'L', 'E', 'E'])
Output: [1, 72]
Example 3
Input: count_regions_and_selections(['000', '000', '000'], ['G', 'O', 'L', 'E'])
Output: [0, 0]
Example 4
Input: count_regions_and_selections(['10101', '00000', '10101'], ['G', 'O', 'O', 'G', 'L', 'E', 'G', 'O', 'O', 'G', 'L', 'E'])
Output: [6, 144]
Hints
Hint 1
For land regions: use breadth-first search to explore each connected component, marking cells as visited when you add them to the queue to avoid duplicates
Hint 2
For letter selection: the target word GOOGLE requires exactly 2 G's, 2 O's, 1 L, and 1 E. Count how many of each letter you have available
Hint 3
The number of ways to form GOOGLE is the product of combination counts: C(available_G, 2) × C(available_O, 2) × C(available_L, 1) × C(available_E, 1)
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has two independent parts that require different algorithmic techniques.
Part 1: Counting Land Regions
We need to find connected components of land cells in the grid. The approach:
- Iterate through every cell in the grid
- When we encounter an unvisited land cell (
'1'), we've discovered a new region - Use breadth-first search (BFS) to explore the entire connected component, marking all reachable land cells as visited
- Continue scanning for the next unvisited land cell
Why BFS instead of DFS? While recursive depth-first search works conceptually, it risks stack overflow on large grids. A grid that is entirely land (e.g., 1000×1000) would require ~1,000,000 recursive calls, exceeding Python's default recursion limit. Iterative BFS with a queue avoids this issue entirely.
Critical detail: Mark cells as visited when enqueuing them, not when dequeuing. Otherwise, the same cell can be added multiple times by different neighbors, causing unnecessary queue growth.
Time Complexity: O(m × n) where m and n are grid dimensions. Each cell is examined once during the scan and enqueued at most once during BFS.
Space Complexity: O(m × n) for the visited matrix and the BFS queue in worst case.
Part 2: Counting Letter Selections
The word GOOGLE requires exactly 2 G's, 2 O's, 1 L, and 1 E. Since the selected letters will be rearranged, the order of selection doesn't matter—only which array positions we choose.
The key insight: selections for each required letter are independent. We can:
- Count available occurrences of each letter in the input array
- For each required letter, calculate how many ways to choose the needed quantity from available positions
- Multiply these independent choices together
The formula: C(g,2) × C(o,2) × C(l,1) × C(e,1) where g, o, l, e are the counts of each letter.
If any letter has insufficient occurrences (e.g., only 1 G when we need 2), the result is 0.
Why combinations not permutations? We're choosing a set of indices, not an ordered sequence. Selecting indices {0, 2} for the G's is one way, not two.
Time Complexity: O(k) where k = len(letters), for building the frequency counter.
Space Complexity: O(1) beyond input, since the counter holds at most 26 distinct letters.
Complete Solution
from collections import Counter, deque
from math import comb
from typing import List
def count_regions_and_selections(grid: List[str], letters: List[str]) -> List[int]:
# Task 1: Count land regions using BFS
if not grid or not grid[0]:
region_count = 0
else:
rows = len(grid)
cols = len(grid[0])
visited = [[False] * cols for _ in range(rows)]
region_count = 0
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
for row in range(rows):
for col in range(cols):
if grid[row][col] != '1' or visited[row][col]:
continue
region_count += 1
visited[row][col] = True
queue = deque([(row, col)])
while queue:
curr_row, curr_col = queue.popleft()
for delta_row, delta_col in moves:
next_row = curr_row + delta_row
next_col = curr_col + delta_col
if (
0 <= next_row < rows
and 0 <= next_col < cols
and not visited[next_row][next_col]
and grid[next_row][next_col] == '1'
):
visited[next_row][next_col] = True
queue.append((next_row, next_col))
# Task 2: Count ways to select letters forming GOOGLE
letter_counts = Counter(letters)
target = {'G': 2, 'O': 2, 'L': 1, 'E': 1}
selection_count = 1
for character, required in target.items():
available = letter_counts[character]
if available < required:
selection_count = 0
break
selection_count *= comb(available, required)
return [region_count, selection_count]