KatInterview

Anti-Diagonal Cell in Outward Spiral Matrix

Math & Bit ManipulationAuto-graded · 22 test cases

Last updated

Finding a specific value in a spiral-filled matrix using mathematical properties of concentric rings rather than simulation.

You are given an odd integer n representing the size of a square matrix. This matrix is populated with consecutive integers from 1 to n² following a specific pattern: starting from the central cell with 1, numbers are placed in a clockwise spiral expanding outward toward the edges.

Your task is to determine which number appears at a particular position on the anti-diagonal of this matrix.

Spiral Construction

The spiral begins at the center cell and proceeds clockwise in the following pattern:

  • Move right 1 step, then down 1 step
  • Move left 2 steps, then up 2 steps
  • Move right 3 steps, then down 3 steps
  • Move left 4 steps, then up 4 steps
  • Continue this pattern...

Each pair of moves increases the step count by one. The sequence completes when all n² cells are filled, with the final value appearing at the top-right corner.

Anti-Diagonal Definition

The anti-diagonal consists of all cells (i, n - 1 - i) where i ranges from 0 to n - 1. This diagonal runs from the top-right corner down to the bottom-left corner.

Task

Given n and an offset k, find the value at the anti-diagonal cell in row center + k, where center = (n - 1) // 2.

  • When k is negative, you're looking at rows above the center
  • When k is positive, you're looking at rows below the center
  • When k is zero, you're looking at the center row itself

The row index is r = center + k, and the corresponding anti-diagonal cell is at position (r, n - 1 - r).

Constraints

  • n is an odd integer where 1 <= n <= 1001
  • k is an integer where -(n-1)//2 <= k <= (n-1)//2
  • The result will be between 1 and n²

Examples

Example 1

Input: spiral_anti_diagonal_value(5, -1)

Output: 9

Example 2

Input: spiral_anti_diagonal_value(5, 2)

Output: 17

Example 3

Input: spiral_anti_diagonal_value(7, 3)

Output: 37

Hints

Hint 1

The anti-diagonal cells all lie at corners of the concentric square rings formed by the spiral

Hint 2

Each ring d has a predictable pattern: the outer corner that completes the square has a value of (2d+1)²

Hint 3

You can determine which corner of which ring your target cell corresponds to based on the sign and magnitude of k