Torna alle sfide
Media 0 risolte 0% di accettazione

Number Spiral Lookup

Find a value by row and column in an expanding number spiral.

Cosa imparerai

  • Find a formula in a number pattern
  • Split the problem by layer and parity
  • Use 64-bit integers for large values

Problema

Mostra traduzione

The infinite spiral starts at the top-left cell. The first four rows and columns are shown below. Continue the same pattern in expanding square layers. Coordinates start at 1.

 1   2   9  10
 4   3   8  11
 5   6   7  12
16  15  14  13

Return one cell value without constructing the entire grid.

Implement number_spiral(row, column).

Input

row: The row counted from the top, starting at 1.

column: The column counted from the left, starting at 1.

Output

Return the number at that position.

Vincoli

1 ≤ row, column ≤ 1,000,000,000. The value fits a signed 64-bit integer.

Esempi

Esempio 1
Input:
row = 3
column = 2

Output atteso:
expected = 6
Input:
long long row = 3;
long long column = 2;

Output atteso:
long long expected = 6;
Input:
long row = 3;
long column = 2;

Output atteso:
long expected = 6;

Spiegazione

In the displayed third row, the second value is 6.

Esempio 2
Input:
row = 1
column = 4

Output atteso:
expected = 10
Input:
long long row = 1;
long long column = 4;

Output atteso:
long long expected = 10;
Input:
long row = 1;
long column = 4;

Output atteso:
long expected = 10;

Spiegazione

The fourth square layer begins at 10 in the top row.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

The spiral is built in square layers, so a cell belongs to a layer determined by the larger coordinate.

Suggerimento 2

Use the parity of that layer to decide whether values increase along a row or a column.

Suggerimento 3

Pay attention to whether the layer reaches from the top-left corner or the opposite corner first.

Complessità attesa

O(1) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.