Anti-Diagonal Entry in an Outward Clockwise Spiral Grid
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Consider an odd-dimensional n x n grid populated with consecutive integers from 1 through n * n along an outward clockwise spiral originating at the center cell. Given the grid width n and a signed vertical offset k relative to the center row, compute the integer located on the anti-diagonal (top-right to bottom-left diagonal) in that offset row.
def spiral_anti_diagonal_value(n: int, k: int) -> int:
Grid layout and traversal rules:
- Indexing: Rows are indexed
0throughn - 1top-to-bottom and columns0throughn - 1left-to-right. Definingm = (n - 1) // 2, the center coordinate is(m, m). - Outward clockwise fill: Cell
(m, m)receives1. From there, advance one cell per step and write2, 3, ..., n * nwhile cycling directions in the order right, down, left, up with leg lengths1, 1, 2, 2, 3, 3, 4, 4, ...(each pair of legs shares a length before the length increments by1). Traversal halts as soon asn * nis placed in the top-right cell(0, n - 1). - Target coordinate: For row index
r = m + k(k < 0moves upward,k == 0stays on the center row,k > 0moves downward), the anti-diagonal column is(n - 1) - r. Return the value at(r, n - 1 - r).
For n = 3 (m = 1), the populated grid is:
7 8 9
6 1 2
5 4 3
Examples
Example 1
Input: n = 3, k = 1
Output: 5
With m = 1, offset k = 1 selects row r = 2 (the bottom row) and anti-diagonal column 3 - 1 - 2 = 0. Cell (2, 0) in the 3 x 3 grid above contains 5.
Example 2
Input: n = 7, k = -2
Output: 25
Here m = 3, so r = 3 - 2 = 1 and the anti-diagonal column is 7 - 1 - 1 = 5. Cell (1, 5) is the top-right corner of the centered 5 x 5 layer, where that layer finishes at 5 * 5 = 25.
Example 3
Input: n = 9, k = 4
Output: 65
With m = 4, r = 4 + 4 = 8 selects the bottom-left corner (8, 0) of the 9 x 9 grid. The 9 x 9 outer border ends with 81 at (0, 8), and stepping backward two sides of 8 steps each reaches (8, 0) at 81 - 16 = 65.
Constraints
1 <= n <= 1001, andnis always odd.-m <= k <= m, wherem = (n - 1) // 2.
Step-by-step walkthrough
Understand the grid coordinates and anti-diagonal
In an odd
n x ngrid, the middle index ism = (n - 1) // 2, placing the starting cell1at(m, m). Becausenis odd,n - 1equals2 * m.The anti-diagonal (also called the secondary diagonal) runs from the top-right corner
(0, n - 1)down to the bottom-left corner(n - 1, 0). In rowr, its column index is(n - 1) - r. Substitutingr = m + kandn - 1 = 2 * msimplifies our target cell cleanly:target_row = m + ktarget_col = 2 * m - (m + k) = m - k
So we always want the number at
(m + k, m - k). Marking those[diagonal]cells on a5 x 5spiral (m = 2) reveals a striking pattern:col 0 col 1 col 2 col 3 col 4 row 0 21 22 23 24 [25] <- k = -2 (row 0, col 4) row 1 20 7 8 [9] 10 <- k = -1 (row 1, col 3) row 2 19 6 [1] 2 11 <- k = 0 (row 2, col 2) row 3 18 [5] 4 3 12 <- k = +1 (row 3, col 1) row 4 [17] 16 15 14 13 <- k = +2 (row 4, col 0)Going upward and rightward from
[1], the entries read1, 9, 25—the odd squares1^2, 3^2, 5^2! Let's see why that always holds.Brute force first: simulate the spiral walk
A direct approach allocates an
n x n2D array, writes1at(m, m), and steps cell by cell (1right,1down,2left,2up,3right,3down, ...) untiln * n, finally returninggrid[m + k][m - k].Because
n <= 1001has at most1,002,001cells,O(n^2)simulation works well as a unit-test oracle on small grids. Still, building a million-element table to look up one integer wastesO(n^2)time and memory—and fails completely ifnscales to10^9. Since(m + k, m - k)sits at a corner of a concentric square layer, we can evaluate it directly inO(1)arithmetic.Key observation: the walk wraps one square ring at a time
Partition the grid into concentric square frames (rings) around
(m, m):- Ring 0: the
1 x 1center(m, m), containing1. - Ring 1: the
3 x 3border surrounding the center (8cells), containing2through9. - Ring 2: the
5 x 5border surrounding Ring 1 (16cells), containing10through25. - Ring
r: the outer border of a(2*r + 1)by(2*r + 1)centered square.
+--------------------+ | 21 22 23 24 25 | <- Ring 2 (5x5 square, finishes at top-right with 5^2 = 25) | +------------+ | | 20| 7 8 9 |10 | <- Ring 1 (3x3 square, finishes at top-right with 3^2 = 9) | | +----+ | | | 19| 6| 1 | 2 |11 | <- Ring 0 (1x1 square, finishes at center with 1^2 = 1) | | +----+ | | | 18| 5 4 3 |12 | | +------------+ | | 17 16 15 14 13 | +--------------------+Why does every ring
r >= 1finish at its top-right corner(m - r, m + r)with(2*r + 1)^2? Trace what happens right after ringr - 1finishes at(m - r + 1, m + r - 1):- Step into ring
r: 1 cell right to(m - r + 1, m + r). - Right border:
2*r - 1cells down to bottom-right(m + r, m + r). - Bottom border:
2*rcells left to bottom-left(m + r, m - r). - Left border:
2*rcells up to top-left(m - r, m - r). - Top border:
2*rcells right to top-right(m - r, m + r).
At that instant, the walk has filled every cell of the
(2*r + 1)by(2*r + 1)centered square without stepping outside it, so(m - r, m + r)holds(2*r + 1)^2!- Ring 0: the
Find the corner values of ring r
Each side of a
(2*r + 1)by(2*r + 1)square contains2*r + 1cells, so walking from one corner to the next corner along an edge takes2*rsteps (just like 5 fence posts span 4 intervals).Because the clockwise walk visits
bottom-right -> bottom-left -> top-left -> top-right, stepping backward from the top-right corner subtracts2*rper side:top-left (m - r, m - r) top-right (m - r, m + r) (2*r + 1)^2 - 2*r ---2r---> (2*r + 1)^2 ^ | 2r | bottom-left (m + r, m - r) bottom-right (m + r, m + r) (2*r + 1)^2 - 4*r <---2r--- (2*r + 1)^2 - 6*rChecking Ring 1 (
r = 1,2*r = 2,(2*r + 1)^2 = 9) on the3 x 3grid confirms all four corners: top-right9, top-left9 - 2 = 7, bottom-left9 - 4 = 5, bottom-right9 - 6 = 3.Match the target cell (m + k, m - k) to its corner
Substitute
ring = abs(k)into(m + k, m - k):- When
k < 0:k = -ring, giving(m - ring, m + ring)—the top-right corner ofring, which holds(2 * ring + 1)^2. - When
k == 0:ring = 0, giving(m, m)with value1. Since(2 * 0 + 1)^2 = 1,k <= 0handles both cases together! - When
k > 0:k = +ring, giving(m + ring, m - ring)—the bottom-left corner ofring, which holds(2 * ring + 1)^2 - 4 * ring.
Notice that
ndrops out of the formula completely: because the spiral grows outward from(m, m), ringrholds identical values inside any oddn x ngrid large enough to contain it (-m <= k <= m).def spiral_anti_diagonal_value(n: int, k: int) -> int: # Let m = (n - 1) // 2. Target row is m + k and target column is (n - 1) - (m + k) = m - k, # which sits on a corner of concentric square ring r = abs(k) around the center (m, m). ring = abs(k) # Ring r is the outer border of a (2*r + 1) by (2*r + 1) centered square, # whose clockwise walk always finishes at its top-right corner with (2*r + 1)^2. side_length = 2 * ring + 1 top_right_value = side_length * side_length # k <= 0 lands on the top-right corner (or center 1 when k == 0). if k <= 0: return top_right_value # k > 0 lands on the bottom-left corner, reached two sides (2 * ring steps each) # before the top-right corner during the clockwise walk. steps_per_side = 2 * ring return top_right_value - 2 * steps_per_side- When
Trace the three examples
Example 1: n = 3, k = 1 ring = abs(1) = 1 side_length = 2 * 1 + 1 = 3 top_right_value = 3 * 3 = 9 k > 0 -> steps_per_side = 2 -> return 9 - 2 * 2 = 5 Example 2: n = 7, k = -2 ring = abs(-2) = 2 side_length = 2 * 2 + 1 = 5 top_right_value = 5 * 5 = 25 k <= 0 -> return 25 Example 3: n = 9, k = 4 ring = abs(4) = 4 side_length = 2 * 4 + 1 = 9 top_right_value = 9 * 9 = 81 k > 0 -> steps_per_side = 8 -> return 81 - 2 * 8 = 65Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def spiral_anti_diagonal_value(n: int, k: int) -> int: # Let m = (n - 1) // 2. Target row is m + k and target column is (n - 1) - (m + k) = m - k, # which sits on a corner of concentric square ring r = abs(k) around the center (m, m). ring = abs(k) # Ring r is the outer border of a (2*r + 1) by (2*r + 1) centered square, # whose clockwise walk always finishes at its top-right corner with (2*r + 1)^2. side_length = 2 * ring + 1 top_right_value = side_length * side_length # k <= 0 lands on the top-right corner (or center 1 when k == 0). if k <= 0: return top_right_value # k > 0 lands on the bottom-left corner, reached two sides (2 * ring steps each) # before the top-right corner during the clockwise walk. steps_per_side = 2 * ring return top_right_value - 2 * steps_per_side✅ Submit now — all tests should pass.
Intuition & how it works
Picture laying numbered square tiles outward from a center tile 1 like coiling a rope into concentric square frames (1 x 1, 3 x 3, 5 x 5, and so on). Each time the clockwise coil completes a (2*r + 1) by (2*r + 1) frame (ring r), it has placed every integer from 1 through (2*r + 1)^2, ending right in that frame's top-right corner. Meanwhile, the anti-diagonal (also called the secondary diagonal—the line of cells running from top-right to bottom-left) slices directly through the top-right and bottom-left corners of every single concentric frame!
A brute-force solution builds an n x n 2D array, walks all n * n steps (1 right, 1 down, 2 left, 2 up, ...), and reads off one cell. That allocates up to 1,002,001 entries for n <= 1001 and becomes completely infeasible if n grows to 10^9.
Instead, we evaluate a closed-form formula (a fixed arithmetic expression with zero loops) by locating which concentric ring (square shell at Chebyshev distance r = abs(k) from (m, m)) owns (m + k, m - k):
- In Example 1 (
n = 3, k = 1,m = 1), moving1row down and1column left from(1, 1)reaches(2, 0), the bottom-left corner ofring = 1(3 x 3). Stepping backward two sides of2 * 1 = 2cells from top-right3^2 = 9gives9 - 4 = 5. - In Example 2 (
n = 7, k = -2,m = 3), moving2rows up and2columns right reaches(1, 5), the top-right corner ofring = 2(5 x 5), which holds(2 * 2 + 1)^2 = 25.
Complexity
- Time:
O(1). Evaluatingabs(k)and a handful of integer multiplications and subtractions takes constant time with zero loops, independent ofn. - Space:
O(1). Only three scalar integer variables are used; no grid is allocated.
Edge cases
- Smallest grid
n = 1, k = 0:ring = 0,side_length = 1, returning1for(0, 0). - Center row
k = 0for any oddn: Lands on(m, m)and returns1. - Outer top-right corner (
k = -m):ring = mgives(2 * m + 1)^2 = n * n, the final number written by the walk. - Outer bottom-left corner at maximum
n = 1001, k = 500: Computes1001^2 - 4 * 500 = 1,002,001 - 2,000 = 1,000,001, fitting comfortably inside a 32-bit signed integer. - Invariance across
n:spiral_anti_diagonal_value(7, -2)andspiral_anti_diagonal_value(999, -2)both return25because outer rings never alter inner rings.
Common mistakes
- Indexing the main diagonal instead of the anti-diagonal: Reading
(m + k, m + k)inspects top-left to bottom-right (3instead of5onn = 3, k = 1), whereas(r, n - 1 - r)simplifies to(m + k, m - k). - Reversing the sign of
k: Negativekmoves toward row0(up and right toward top-right); swappingk <= 0andk > 0returns9instead of5on Example 1 (n = 3, k = 1). - Subtracting
2 * ring + 1per edge instead of2 * ring: A side containing2 * ring + 1cells has2 * ringsteps from corner to corner; subtracting2 * ring + 1double-counts the shared corner cell. - Assuming the wrong corner holds
(2 * r + 1)^2: Because this spiral steps right first and turns clockwise, each odd square lands at top-right; spirals that start upward or turn counterclockwise finish at different corners. - Stepping out of bounds at
n * nduring simulation: The final rightward run has nominal lengthnbut onlyn - 1columns remain before(0, n - 1), so a simulator must stop as soon asvalue == n * n.
Alternative approaches
- Full 2D simulation: Populate an
n x nlist of lists by walking right, down, left, up with run lengths1, 1, 2, 2, ...up ton * n. CostsO(n^2)time andO(n^2)memory—ideal as a randomized test reference for small oddn. - Coordinate-only walk: Track
(row, col, value)without storing the grid and returnvalueonce(row, col) == (m + k, m - k). UsesO(1)memory while still takingO(n^2)worst-case steps.
Follow-up questions
- How can you compute the entry at an arbitrary coordinate (row, col) in O(1) time without building the grid? Identify the concentric ring
r = max(abs(row - m), abs(col - m))(return1whenr == 0). That ring finishes at top-right(m - r, m + r)withend = (2 * r + 1)^2, and walking backward along its four borders subtracts the step distance fromend: on the top border (row == m - r) returnend - ((m + r) - col); else on the left border (col == m - r) returnend - 2 * r - (row - (m - r)); else on the bottom border (row == m + r) returnend - 4 * r - (col - (m - r)); else on the right border (col == m + r) returnend - 6 * r - ((m + r) - row). Usingif / elifhandles shared corners cleanly inO(1)time and space. - How does the closed-form calculation change if the spiral steps upward first or winds counterclockwise? Because segment lengths still follow
1, 1, 2, 2, 3, 3, ..., every ringrstill finishes a complete(2 * r + 1)^2centered square—only the finishing corner and backward edge order rotate or reflect. Sketch the3 x 3case (n = 3) to see which corner receives9and which direction walks backward from9, then subtract2 * rper side in that order. - How would you find the sum of all entries along the anti-diagonal for a given odd dimension n? Add
1(the center atk = 0) to the sum over ringsr = 1 .. m(m = (n - 1) // 2) of each ring's top-right and bottom-left corners:(2 * r + 1)^2 + ((2 * r + 1)^2 - 4 * r) = 8 * r^2 + 4 * r + 2. You can either accumulate that expression in anO(n)loop or apply the closed-form identities1 + 2 + ... + m = m * (m + 1) // 2and1^2 + 2^2 + ... + m^2 = m * (m + 1) * (2 * m + 1) // 6for anO(1)formula.
Follow-up questions
- How can you compute the entry at an arbitrary coordinate (row, col) in O(1) time without building the grid?
- How does the closed-form calculation change if the spiral steps upward first or winds counterclockwise?
- How would you find the sum of all entries along the anti-diagonal for a given odd dimension n?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array