Sparse Vector Overlap Sum and Land Cluster Counter
Trees & GraphsAuto-graded · 17 test casesLast updated
Combine a merge-style sparse vector dot product with an iterative flood fill that counts 4-connected land clusters, returning both results together.
Write one function that answers two independent questions and returns both answers together.
Part A: Sparse vector dot product
Two long vectors of the same length n are stored sparsely. Each vector is a list of [index, value] pairs, one pair for each position holding a non-zero value. Every position not listed is zero. Each list is sorted by index in increasing order, and an index appears at most once per list.
Compute the dot product of the two vectors, that is, the sum over all positions of the product of the two entries at that position. Only positions present in both lists can contribute. Values may be negative.
Part B: Counting land clusters
You are also given a rectangular grid whose cells hold "1" (land) or "0" (water). A cluster is a maximal group of land cells in which any two cells are linked by a chain of land cells, each step moving up, down, left, or right. Cells that touch only diagonally are not connected.
Count the clusters in the grid. An empty grid, or a grid with no land, has zero clusters. A land cell may also be given as the integer 1; treat it the same as "1".
Output
Return a list of two integers: [dot_product, cluster_count].
Constraints
nis the common length of both vectors and can be as large as 100,000. Every index is in[0, n-1].- Each sparse list is sorted by index, with no repeated indices within a list. Either list may be empty.
- Values are integers and may be negative.
- The grid may be empty, may be a single row or column, and may be large, so a deep recursion can overflow the stack. Prefer an explicit stack or queue.
- The running time should be proportional to the number of stored entries for Part A, and to the number of grid cells for Part B.
- You may modify the grid in place or use extra memory.
Examples
Example 1
Input: sparse_overlap_and_land_clusters([[0, 2], [3, 4]], [[0, 5], [2, 7]], 5, [['1', '0'], ['0', '1']])
Output: [10, 2]
Example 2
Input: sparse_overlap_and_land_clusters([[1, -2], [4, 3]], [[0, 8], [1, 5], [4, -1]], 6, [['1', '1', '0'], ['0', '1', '0'], ['0', '0', '1']])
Output: [-13, 2]
Example 3
Input: sparse_overlap_and_land_clusters([], [], 0, [])
Output: [0, 0]
Hints
Hint 1
Both lists are sorted by index, so you can walk them together with two pointers, like the merge step of merge sort. You never need to build dense arrays of length n.
Hint 2
When the indices at the two pointers differ, the entry with the smaller index has no partner, so skip it. When they match, multiply and advance both pointers.
Hint 3
For the grid, scan every cell. Each time you meet unvisited land, add one to the count and flood-fill its whole cluster with an explicit stack or queue, marking cells as visited when you push them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two parts are independent, so we solve each and return the pair.
Part A: two pointers over sorted entries
A position adds to the dot product only if both vectors are non-zero there. Because both lists are sorted by index, we walk them together like the merge step of merge sort:
- If the two indices are equal, add the product of the values and advance both pointers.
- If the index in
ais smaller,bis zero at that position (its remaining indices are all larger), so skip the entry ina. - Otherwise skip the entry in
b.
We stop when either list is exhausted, since the leftover entries of the other list would multiply against zeros.
Why it is correct: every index below the smaller of the two current indices has already been handled. A skipped entry cannot have a partner in the other sorted list, so it contributes nothing. Every shared index is met exactly once and its product is added once.
Part B: flood fill and count the starts
Scan the cells in row-major order. When a land cell is found, it is the first cell of a new cluster: increment the counter, then flood-fill the whole cluster using an explicit stack, turning each visited land cell into '0'. Cells are marked when pushed, so each cell enters the stack at most once. An explicit stack avoids recursion-depth failures on large or snake-shaped clusters.
Why it is correct: each flood fill visits exactly the cluster containing its start cell, because it expands only through 4-adjacent land and reaches every cell connected to the start. Visited cells are erased, so the scan never starts a second fill inside a counted cluster. Each cluster is therefore counted exactly once. Diagonal neighbours are never examined, so they stay separate. An empty grid or a grid with no land gives 0.
Complexity
- Part A: time O(k1 + k2) where k1 and k2 are the numbers of stored entries; extra space O(1). It does not depend on
n. - Part B: time O(m * n_cols), since each cell is scanned once and pushed at most once; space O(m * n_cols) in the worst case for the stack (an all-land grid).
Reference solution
from typing import List
def sparse_overlap_and_land_clusters(a: List[List[int]], b: List[List[int]], n: int, grid: List[List[str]]) -> List[int]:
# Part A: two-pointer merge over sorted sparse entries
i = j = 0
dot = 0
while i < len(a) and j < len(b):
ia, va = a[i]
ib, vb = b[j]
if ia == ib:
dot += va * vb
i += 1
j += 1
elif ia < ib:
i += 1
else:
j += 1
# Part B: iterative flood fill, marking cells when pushed
clusters = 0
rows = len(grid)
for r in range(rows):
for c in range(len(grid[r])):
if grid[r][c] != '1' and grid[r][c] != 1:
continue
clusters += 1
grid[r][c] = '0'
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < len(grid[nr]):
if grid[nr][nc] == '1' or grid[nr][nc] == 1:
grid[nr][nc] = '0'
stack.append((nr, nc))
return [dot, clusters]