KatInterview

Target-Sum Windows and Largest Building Cluster

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingprefix-sumhash-mapflood-fill

Last 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^7
  • 1 <= rows, cols <= 300, where rows = len(city) and cols = len(city[i])
  • Each grid cell is either 0 or 1.
  • 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.