Combine Overlapping Ranges and Count Unique Land Shapes
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Merge overlapping or touching closed ranges, and count land regions in a binary grid that differ in shape when only shifting is allowed.
Combine Overlapping Ranges and Count Unique Land Shapes
You are given two independent inputs, and one function must answer both questions about them.
Part A: Ranges
ranges is a list of closed ranges [start, end], with start <= end. The list may be unsorted and may contain duplicates.
Combine every group of ranges that overlap or touch at an endpoint (for example [1,4] and [4,5] become [1,5]) into a single range. Return the resulting ranges in ascending order of start. The combined ranges must be pairwise disjoint and must not touch each other.
If ranges is empty, the result is an empty list. Do not modify the input.
Part B: Land shapes
grid is a 2D list containing only 0 (water) and 1 (land). A region is a maximal set of land cells connected through their four neighbors (up, down, left, right). Diagonal cells are not connected.
Two regions have the same shape if one can be moved onto the other purely by sliding it (translation). Rotating or mirroring a region does not make it the same shape; a rotated or mirrored copy counts as a different shape unless it also happens to match by translation.
Count how many different shapes appear among the regions. If the grid is empty or contains no land, the count is 0.
Output
Return a dictionary with exactly two keys:
{"merged_intervals": <list of [start, end] lists>, "distinct_islands": <int>}
Constraints
0 <= len(ranges) <= 10^4; each range is[start, end]with integers andstart <= end.0 <= rows, cols <= 50(grid may be empty); all rows have equal length.- Each grid value is
0or1. - Touching ranges (sharing an endpoint) must be combined.
- Only 4-directional connectivity is used.
- The two parts are independent of each other.
Examples
Example 1
Input: merge_ranges_count_shapes([[1, 3], [2, 6], [8, 10], [15, 18]], [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]])
Output: {'merged_intervals': [[1, 6], [8, 10], [15, 18]], 'distinct_islands': 1}
Example 2
Input: merge_ranges_count_shapes([[1, 4], [4, 5]], [[1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]])
Output: {'merged_intervals': [[1, 5]], 'distinct_islands': 2}
Example 3
Input: merge_ranges_count_shapes([], [[1, 1, 0], [0, 0, 1], [1, 1, 0]])
Output: {'merged_intervals': [], 'distinct_islands': 2}
Hints
Hint 1
Sort the ranges by start. After sorting, a range can only overlap the most recently built block, so a single left-to-right pass works.
Hint 2
When extending the last block, set its end to the maximum of the old end and the new end, so a range nested inside a larger one does not shrink it. Merge when start <= last end (touching counts).
Hint 3
For shapes, flood-fill each region starting from the first cell found in row-major order, and store every cell as an offset from that first cell. Put the sorted offsets in a set as a tuple and return the set's size.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two parts are independent, so each is solved on its own.
Part A: merging ranges
- Sort the ranges by start (
sortedreturns a new list, so the input is untouched). - Sweep left to right, keeping a list of merged blocks.
- If there is no block yet, or the current start is strictly greater than the last block's end, begin a new block.
- Otherwise the range overlaps or touches the last block, so set that block's end to
max(old_end, end).
Why it is correct: after sorting, starts never decrease. If a range begins beyond the current block's end, every later range begins even further right, so nothing can reach back into that block and it is final. If it does overlap, the union is a single contiguous range ending at the larger of the two ends. The max handles nested ranges. Using > rather than >= is what makes touching ranges merge.
Part B: counting shapes up to translation
- Scan cells in row-major order. An unvisited land cell starts a new region and serves as its anchor.
- Flood-fill the region with an iterative DFS using a stack, marking cells visited when pushed.
- Record each cell as an offset
(x - anchor_row, y - anchor_col). - Sort the offsets and store them as a tuple in a set. The answer is the set size.
Why it is correct: in row-major order the first cell reached in a region is its top-most, left-most cell. Translated copies of a shape therefore have the anchor at the same place in the shape, giving identical offset sets. Conversely, identical offset sets mean one region is the other shifted by the difference of anchors. Sorting removes any dependence on traversal order. Rotations and mirror images produce different offset sets, matching the rules.
Complexity
- Part A: time O(n log n), space O(n).
- Part B: with R x C cells, time O(RC log(RC)) in the worst case because of sorting offsets, space O(R*C).
Reference solution
from typing import List, Dict
def merge_ranges_count_shapes(ranges: List[List[int]], grid: List[List[int]]) -> Dict[str, object]:
merged = []
for start, end in sorted(ranges):
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
rows = len(grid)
cols = len(grid[0]) if rows else 0
seen = [[False] * cols for _ in range(rows)]
shapes = set()
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
stack = [(r, c)]
seen[r][c] = True
cells = []
while stack:
x, y = stack.pop()
cells.append((x - r, y - c))
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1 and not seen[nx][ny]:
seen[nx][ny] = True
stack.append((nx, ny))
shapes.add(tuple(sorted(cells)))
return {"merged_intervals": merged, "distinct_islands": len(shapes)}