KatInterview

Matrix 90-Degree Clockwise Rotation and Maximum Interval Coverage

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalsarraysgreedy-intervalsheaps-sorting

Last 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.

  1. Out-of-Place Implementation: Implement a solution that constructs a new matrix in $O(n^2)$ time.
  2. 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.
  3. 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:

  1. Determine the maximum number of overlapping transmitters covering any single point along the 1D line.
  2. 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.