Matrix 90-Degree Clockwise Rotation and Maximum Interval Coverage
Greedy & IntervalsModel answerLast updated
Rotate a square grid 90 degrees clockwise and identify regions of maximal overlapping intervals using a sweep-line algorithm.
This technical assessment consists of two independent parts involving array transformations and coordinate geometry.
Part 1: Grid Rotation
Given an $n \times n$ 2D matrix of integers, construct and return a new $n \times n$ matrix representing a 90-degree clockwise rotation of the input.
- Out-of-Place Implementation: Implement a solution that constructs a new matrix in $O(n^2)$ time.
- In-Place Discussion: Explain how to modify the grid in-place using $O(1)$ auxiliary space. Compare the trade-offs between space complexity, execution speed, and functional side-effects.
- Edge Cases: Detail boundary conditions (such as $1 \times 1$ matrices, empty grids, odd vs. even values of $n$, and negative values).
Part 2: Maximum Interval Overlap
Consider $N$ active continuous transmitters situated along a 1D line. Each transmitter $i$ is positioned at coordinate $x_i$ and has a coverage radius $r_i$, illuminating the inclusive closed segment $[x_i - r_i, x_i + r_i]$.
Write an algorithm to:
- Determine the maximum number of overlapping transmitters covering any single point along the 1D line.
- Return all maximal closed segments (intervals) $[a, b]$ where this maximum overlap count is maintained, sorted by coordinate.
Constraints:
- $1 \le N \le 2 \times 10^5$
- $-10^9 \le x_i \le 10^9$
- $1 \le r_i \le 10^9$
Requirements:
- Design an $O(N \log N)$ time and $O(N)$ space algorithm (such as a sweep-line approach).
- Prove the correctness of your endpoint handling and gap evaluation logic.
- Discuss how the logic changes if intervals are strictly open $(x_i - r_i, x_i + r_i)$ or limited to integer coordinates.
Hints
Hint 1
For matrix rotation, map the indices: input element (r, c) moves to target position (c, n - 1 - r).
Hint 2
For in-place matrix rotation, a common 2-step trick is transposing the matrix along its main diagonal, followed by reversing each row.
Hint 3
For interval overlap, split each interval [x-r, x+r] into discrete start and end events. Be careful to process start events before or alongside end events depending on whether intervals are closed.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Matrix Rotation (90° Clockwise)
1. Mathematical Mapping & Out-of-Place Solution
When rotating an $n \times n$ matrix clockwise by 90 degrees:
- Row $r$ of the original grid becomes Column $n - 1 - r$ in the destination grid.
- Column $c$ of the original grid becomes Row $c$ in the destination grid.
Thus, the transformation rule is: $$\text{rotated}[c][n - 1 - r] = \text{matrix}[r][c]$$
def rotate_matrix_copy(matrix: list[list[int]]) -> list[list[int]]:
"""Rotates an n x n matrix 90 degrees clockwise using O(n^2) auxiliary space."""
if not matrix or not matrix[0]:
return []
n = len(matrix)
rotated = [[0] * n for _ in range(n)]
for r in range(n):
for c in range(n):
rotated[c][n - 1 - r] = matrix[r][c]
return rotated
In Python, this can also be concisely written using built-in operations:
def rotate_matrix_idiomatic(matrix: list[list[int]]) -> list[list[int]]:
return [list(row) for row in zip(*matrix[::-1])]
2. In-Place Rotation Strategy
To transform the matrix in-place with $O(1)$ extra space, two standard approaches exist:
Approach A: Transpose then Reverse Rows (Recommended)
- Transpose: Swap
matrix[i][j]withmatrix[j][i]for all $j > i$. - Reverse Rows: Reverse every row horizontally.
def rotate_matrix_in_place(matrix: list[list[int]]) -> None:
"""Rotates matrix 90 degrees clockwise in-place."""
n = len(matrix)
# 1. Transpose
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 2. Reverse each row
for row in matrix:
row.reverse()
Approach B: Concentric Ring Cycling
Iterate through concentric square layers from the outside in. For a ring at index layer, cycle 4 boundary elements simultaneously using a single temp variable:
$$\text{top} \to \text{right} \to \text{bottom} \to \text{left} \to \text{top}$$
Trade-Off Analysis
| Feature | Out-of-Place | In-Place (Transpose + Reverse) |
|---|---|---|
| Time Complexity | $O(n^2)$ | $O(n^2)$ |
| Space Complexity | $O(n^2)$ | $O(1)$ |
| Data Immutability | Preserves original array | Mutates original array in memory |
| Cache Efficiency | Lower (allocates new contiguous blocks) | High (in-place row reversal hits CPU L1 cache) |
3. Edge Cases & Validation
- Empty / $0 \times 0$ Matrix: Handle safely by returning
[]. - $1 \times 1$ Matrix: Trivial; returned unchanged.
- Odd vs. Even $n$: For odd $n$, the center element $\text{matrix}[\lfloor n/2 \rfloor][\lfloor n/2 \rfloor]$ remains stationary. Transposition automatically preserves this point.
- Negative & Duplicate Elements: Values are moved solely by coordinate index; sign and value parity have zero impact.
Part 2: Maximum Interval Overlap (Sweep-Line Strategy)
1. Conceptual Design
Each transmitter provides coverage over $[x_i - r_i, x_i + r_i]$. To compute maximum overlap in $O(N \log N)$ time, we use a Sweep-Line Algorithm.
Because intervals are closed, a point $c$ receives coverage from:
- Lamps that started at or before $c$.
- Lamps that end at or after $c$.
Thus, at any event coordinate $c$, we track two distinct quantities:
- $\text{point_cov}(c)$: Total count of active intervals strictly at point $c$.
- $\text{gap_cov}(c)$: Total count of active intervals strictly in the open interval $(c, c_{\text{next}})$.
Let $S(c)$ be the count of intervals starting at $c$, and $E(c)$ be the count of intervals ending at $c$. If $\text{cur}$ is the active coverage immediately preceding $c$: $$\text{point_cov}(c) = \text{cur} + S(c)$$ $$\text{gap_cov}(c) = \text{point_cov}(c) - E(c)$$ $$\text{cur}_{\text{next}} = \text{gap_cov}(c)$$
2. Implementation
from collections import defaultdict
def max_transmitter_coverage(transmitters: list[tuple[int, int]]) -> tuple[int, list[tuple[int, int]]]:
"""
Computes peak coverage count and all maximal continuous closed segments achieving this peak.
transmitters: list of (position, radius)
"""
starts = defaultdict(int)
ends = defaultdict(int)
for x, r in transmitters:
starts[x - r] += 1
ends[x + r] += 1
all_coords = sorted(starts.keys() | ends.keys())
point_cov = []
gap_cov = []
cur = 0
for c in all_coords:
p = cur + starts[c]
g = p - ends[c]
point_cov.append(p)
gap_cov.append(g)
cur = g
max_val = max(point_cov) if point_cov else 0
if max_val == 0:
return 0, []
# Reconstruct maximal segments
segments = []
seg_start = None
for i, c in enumerate(all_coords):
p = point_cov[i]
g = gap_cov[i]
# Start a segment if at peak coverage and not currently inside one
if seg_start is None and p == max_val:
seg_start = c
# End a segment if currently inside one and the open gap drops below peak coverage
if seg_start is not None and g != max_val:
segments.append((seg_start, c))
seg_start = None
return max_val, segments
3. Proof of Endpoint Handling & Correctness
- Segment Continuity: Overlap magnitude changes only at discrete event coordinates ($x_i \pm r_i$). Between two adjacent event points $c_k$ and $c_{k+1}$, coverage is strictly constant and equal to $\text{gap_cov}(c_k)$.
- Merging Point Intervals: If two intervals touch at a single point (e.g., $[0, 2]$ and $[2, 4]$), at coordinate $c = 2$:
- $S(2) = 1, E(2) = 1$.
- $\text{point_cov}(2) = 1 + 1 = 2$.
- $\text{gap_cov}(2) = 2 - 1 = 1$. If the maximum overlap is $2$, the segment starts at $2$ ($\text{point_cov}(2) = 2$) and closes immediately at $2$ ($\text{gap_cov}(2) = 1 \ne 2$), resulting in the single point segment $[2, 2]$.
4. Complexity Analysis
- Time Complexity: $O(N \log N)$ to aggregate and sort up to $2N$ event points. The linear pass over distinct coordinates runs in $O(N)$ time.
- Space Complexity: $O(N)$ to store coordinate hash maps and event vectors.
- Integer Ranges: Input coordinates reach up to $\pm 2 \times 10^9$, which fits within standard 64-bit signed integers (
int64_tin C++/Java).
5. Open Intervals Variant Analysis
If coverage intervals are strictly open: $(x_i - r_i, x_i + r_i)$
- Point Coverage Calculation: Endpoints are excluded. $$\text{point_cov}(c) = \text{cur} - E(c)$$ $$\text{gap_cov}(c) = \text{point_cov}(c) + S(c)$$
- Maximal Segments: Because the boundary points $a$ and $b$ are excluded from open intervals, the maximum coverage cannot occur at a single isolated point boundary unless surrounded by open gaps. The resulting maximal sub-segments would themselves be open sets $(a, b)$.