Target-Sum Windows and Largest Building Cluster
Arrays & HashingAuto-graded · 19 test casesLast updated
Combine a prefix-sum hash map to count contiguous slices summing to a target with a grid flood fill to find the largest 4-connected cluster of buildings.
Implement one function that answers two independent questions and returns both answers together.
Question A: Slices with a target total
You get a list of integers values and an integer target. Count how many contiguous, non-empty slices of values add up to exactly target. Slices at different positions count separately, even if they contain the same numbers. Values may be negative or zero.
Question B: Largest building cluster
You get a rectangular grid city, where 1 is a building and 0 is an empty lot. Two buildings belong to the same cluster if you can get from one to the other by repeatedly stepping to an adjacent building directly up, down, left, or right. Diagonal neighbors are not adjacent. Find the number of buildings in the largest cluster. If the grid has no buildings, the answer is 0.
Output
Return a list of two integers: [slice_count, largest_cluster], where slice_count is the answer to Question A and largest_cluster is the answer to Question B.
Constraints
1 <= len(values) <= 2 * 10^4-1000 <= values[i] <= 1000-10^7 <= target <= 10^71 <= rows, cols <= 300, whererows = len(city)andcols = len(city[i])- Each grid cell is either
0or1. - A cluster may contain up to 90,000 cells, so beware of recursion depth limits.
Examples
Example 1
Input: count_slices_and_largest_cluster([1, 1, 1], 2, [[1, 1, 0], [1, 0, 0], [0, 0, 1]])
Output: [2, 3]
Hints
Hint 1
For the first question, define the running prefix sum. A slice ending at the current index sums to target exactly when an earlier prefix sum equals current_prefix - target.
Hint 2
Store how many times each prefix sum has appeared in a dictionary, start it with {0: 1} for the empty prefix, and read the count before adding the current prefix. A sliding window fails because of negative numbers.
Hint 3
For the grid, scan every cell and start a flood fill from each unvisited building, counting cells and tracking the maximum. Use an explicit stack or queue and mark cells visited when they are added, to avoid recursion limits and duplicates.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two questions are independent, so each is solved on its own and the results are combined into a list.
Question A: counting slices with a given total
Let P[i] be the sum of the first i values, with P[0] = 0. The slice from index j to i-1 sums to P[i] - P[j]. This equals target exactly when P[j] = P[i] - target.
Scan left to right while keeping a dictionary of how many times each prefix sum has occurred. At each step:
- Add the current value to the running prefix.
- Add to the answer the number of earlier prefixes equal to
running - target. - Record the current prefix in the dictionary.
The dictionary starts as {0: 1} so that slices beginning at index 0 are counted. Reading before writing guarantees we never pair a prefix with itself, which would correspond to an empty slice (this matters when target = 0).
A sliding window is not suitable, because negative values make prefix sums non-monotonic.
Question B: largest cluster
Treat each building as a node connected to its up/down/left/right building neighbors. A cluster is a connected component. Scan every cell, and whenever an unvisited building is found, flood fill from it with an explicit stack, counting the cells reached. Keep the maximum count.
Cells are marked visited when pushed onto the stack, so each cell enters at most once and is counted exactly once. An explicit stack avoids Python's recursion limit, which a 90,000-cell cluster would exceed, and a separate visited matrix leaves the input unmodified.
Why it is correct
Every slice ending at a given index matches exactly one earlier prefix position, so the count is exact. Every building belongs to exactly one component, and each component is started only once, from its first unvisited cell, so each is measured completely and exactly once.
Complexity
- Question A: O(n) time, O(n) space.
- Question B: O(rows * cols) time, O(rows * cols) space for the visited matrix and stack.
Reference solution
from collections import defaultdict
from typing import List
def count_slices_and_largest_cluster(values: List[int], target: int, city: List[List[int]]) -> List[int]:
# Question A: prefix sums with a frequency map
seen = defaultdict(int)
seen[0] = 1
running = 0
slice_count = 0
for v in values:
running += v
slice_count += seen[running - target]
seen[running] += 1
# Question B: iterative flood fill over 4-connected buildings
rows = len(city)
cols = len(city[0]) if rows else 0
visited = [[False] * cols for _ in range(rows)]
largest = 0
for r in range(rows):
for c in range(cols):
if city[r][c] != 1 or visited[r][c]:
continue
visited[r][c] = True
stack = [(r, c)]
size = 0
while stack:
cr, cc = stack.pop()
size += 1
for nr, nc in ((cr - 1, cc), (cr + 1, cc), (cr, cc - 1), (cr, cc + 1)):
if 0 <= nr < rows and 0 <= nc < cols and city[nr][nc] == 1 and not visited[nr][nc]:
visited[nr][nc] = True
stack.append((nr, nc))
largest = max(largest, size)
return [slice_count, largest]