1155. Spiral Cell Locator

Medium3.5 points estimatedMathsSimulationMatrix

A gardener plants seedlings on an m x n plot in a clockwise spiral. The first seedling goes into the top-left cell (0, 0), then the gardener moves right along the top edge, down the right edge, left along the bottom edge and up the left edge, and keeps spiralling inward with the same turns until every cell holds one seedling.

Given m, n and k, return [row, col] (zero-based) of the cell that receives the k-th seedling, counting from 1. The plot can be enormous, so you cannot walk it. Constraints: 1 <= m, n <= 9*10^7, m * n <= 9*10^15 and 1 <= k <= m * n. Aim for O(log(min(m, n))) time and O(1) space.

Example 1

Input:
m = 3, n = 4, k = 1
Output:
[0,0]
Explanation:

The first planted cell is always the top-left corner (0, 0).

Example 2

Input:
m = 3, n = 4, k = 6
Output:
[2,3]
Explanation:

Row 0 takes 4 cells, then the right column adds (1, 3) and (2, 3), so the 6th cell is (2, 3).

Example 3

Input:
m = 3, n = 4, k = 12
Output:
[1,2]
Explanation:

After the outer ring of 10 cells the walk covers (1, 1) and then (1, 2), which is the 12th cell.

Constraints

1 ≤ m, n ≤ 9*107
m * n ≤ 9*1015
1 ≤ k ≤ m * n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log(min(m, n)))
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…