KatInterview

Island Detection and Letter Selection Counting

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraph-traversalbfsconnected-components

Last 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 ≤ 1000 where m is the number of rows and n is the number of columns
  • Each grid row has exactly n characters
  • Grid cells contain only '0' or '1'
  • 0 ≤ len(letters) ≤ 1000
  • Each element of letters is 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)