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 0 through n - 1 top-to-bottom and columns 0 through n - 1 left-to-right. Defining m = (n - 1) // 2, the center coordinate is (m, m).
  • Outward clockwise fill: Cell (m, m) receives 1. From there, advance one cell per step and write 2, 3, ..., n * n while cycling directions in the order right, down, left, up with leg lengths 1, 1, 2, 2, 3, 3, 4, 4, ... (each pair of legs shares a length before the length increments by 1). Traversal halts as soon as n * n is placed in the top-right cell (0, n - 1).
  • Target coordinate: For row index r = m + k (k < 0 moves upward, k == 0 stays on the center row, k > 0 moves 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, and n is always odd.
  • -m <= k <= m, where m = (n - 1) // 2.

Step-by-step walkthrough

  1. Understand the grid coordinates and anti-diagonal

    In an odd n x n grid, the middle index is m = (n - 1) // 2, placing the starting cell 1 at (m, m). Because n is odd, n - 1 equals 2 * 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 row r, its column index is (n - 1) - r. Substituting r = m + k and n - 1 = 2 * m simplifies our target cell cleanly:

    • target_row = m + k
    • target_col = 2 * m - (m + k) = m - k

    So we always want the number at (m + k, m - k). Marking those [diagonal] cells on a 5 x 5 spiral (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 read 1, 9, 25—the odd squares 1^2, 3^2, 5^2! Let's see why that always holds.

  2. Brute force first: simulate the spiral walk

    A direct approach allocates an n x n 2D array, writes 1 at (m, m), and steps cell by cell (1 right, 1 down, 2 left, 2 up, 3 right, 3 down, ...) until n * n, finally returning grid[m + k][m - k].

    Because n <= 1001 has at most 1,002,001 cells, 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 wastes O(n^2) time and memory—and fails completely if n scales to 10^9. Since (m + k, m - k) sits at a corner of a concentric square layer, we can evaluate it directly in O(1) arithmetic.

  3. 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 1 center (m, m), containing 1.
    • Ring 1: the 3 x 3 border surrounding the center (8 cells), containing 2 through 9.
    • Ring 2: the 5 x 5 border surrounding Ring 1 (16 cells), containing 10 through 25.
    • 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 >= 1 finish at its top-right corner (m - r, m + r) with (2*r + 1)^2? Trace what happens right after ring r - 1 finishes at (m - r + 1, m + r - 1):

    1. Step into ring r: 1 cell right to (m - r + 1, m + r).
    2. Right border: 2*r - 1 cells down to bottom-right (m + r, m + r).
    3. Bottom border: 2*r cells left to bottom-left (m + r, m - r).
    4. Left border: 2*r cells up to top-left (m - r, m - r).
    5. Top border: 2*r cells 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!

  4. Find the corner values of ring r

    Each side of a (2*r + 1) by (2*r + 1) square contains 2*r + 1 cells, so walking from one corner to the next corner along an edge takes 2*r steps (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 subtracts 2*r per 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*r
    

    Checking Ring 1 (r = 1, 2*r = 2, (2*r + 1)^2 = 9) on the 3 x 3 grid confirms all four corners: top-right 9, top-left 9 - 2 = 7, bottom-left 9 - 4 = 5, bottom-right 9 - 6 = 3.

  5. 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 of ring, which holds (2 * ring + 1)^2.
    • When k == 0: ring = 0, giving (m, m) with value 1. Since (2 * 0 + 1)^2 = 1, k <= 0 handles both cases together!
    • When k > 0: k = +ring, giving (m + ring, m - ring)—the bottom-left corner of ring, which holds (2 * ring + 1)^2 - 4 * ring.

    Notice that n drops out of the formula completely: because the spiral grows outward from (m, m), ring r holds identical values inside any odd n x n grid 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
    
  6. 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 = 65
    
  7. Complete 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), moving 1 row down and 1 column left from (1, 1) reaches (2, 0), the bottom-left corner of ring = 1 (3 x 3). Stepping backward two sides of 2 * 1 = 2 cells from top-right 3^2 = 9 gives 9 - 4 = 5.
  • In Example 2 (n = 7, k = -2, m = 3), moving 2 rows up and 2 columns right reaches (1, 5), the top-right corner of ring = 2 (5 x 5), which holds (2 * 2 + 1)^2 = 25.

Complexity

  • Time: O(1). Evaluating abs(k) and a handful of integer multiplications and subtractions takes constant time with zero loops, independent of n.
  • 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, returning 1 for (0, 0).
  • Center row k = 0 for any odd n: Lands on (m, m) and returns 1.
  • Outer top-right corner (k = -m): ring = m gives (2 * m + 1)^2 = n * n, the final number written by the walk.
  • Outer bottom-left corner at maximum n = 1001, k = 500: Computes 1001^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) and spiral_anti_diagonal_value(999, -2) both return 25 because 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 (3 instead of 5 on n = 3, k = 1), whereas (r, n - 1 - r) simplifies to (m + k, m - k).
  • Reversing the sign of k: Negative k moves toward row 0 (up and right toward top-right); swapping k <= 0 and k > 0 returns 9 instead of 5 on Example 1 (n = 3, k = 1).
  • Subtracting 2 * ring + 1 per edge instead of 2 * ring: A side containing 2 * ring + 1 cells has 2 * ring steps from corner to corner; subtracting 2 * ring + 1 double-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 * n during simulation: The final rightward run has nominal length n but only n - 1 columns remain before (0, n - 1), so a simulator must stop as soon as value == n * n.

Alternative approaches

  • Full 2D simulation: Populate an n x n list of lists by walking right, down, left, up with run lengths 1, 1, 2, 2, ... up to n * n. Costs O(n^2) time and O(n^2) memory—ideal as a randomized test reference for small odd n.
  • Coordinate-only walk: Track (row, col, value) without storing the grid and return value once (row, col) == (m + k, m - k). Uses O(1) memory while still taking O(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)) (return 1 when r == 0). That ring finishes at top-right (m - r, m + r) with end = (2 * r + 1)^2, and walking backward along its four borders subtracts the step distance from end: on the top border (row == m - r) return end - ((m + r) - col); else on the left border (col == m - r) return end - 2 * r - (row - (m - r)); else on the bottom border (row == m + r) return end - 4 * r - (col - (m - r)); else on the right border (col == m + r) return end - 6 * r - ((m + r) - row). Using if / elif handles shared corners cleanly in O(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 ring r still finishes a complete (2 * r + 1)^2 centered square—only the finishing corner and backward edge order rotate or reflect. Sketch the 3 x 3 case (n = 3) to see which corner receives 9 and which direction walks backward from 9, then subtract 2 * r per 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 at k = 0) to the sum over rings r = 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 an O(n) loop or apply the closed-form identities 1 + 2 + ... + m = m * (m + 1) // 2 and 1^2 + 2^2 + ... + m^2 = m * (m + 1) * (2 * m + 1) // 6 for an O(1) formula.

Follow-up questions

Similar questions

More Garmin interview questions

All 1 Garmin questions →