मध्यम 0 हल किए गए 0% स्वीकृति

Number Spiral Lookup

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

आप क्या सीखेंगे

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

समस्या

अनुवाद दिखाएँ

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.

सीमाएँ

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

उदाहरण

उदाहरण 1
इनपुट:
row = 3
column = 2

अपेक्षित आउटपुट:
expected = 6
इनपुट:
long long row = 3;
long long column = 2;

अपेक्षित आउटपुट:
long long expected = 6;
इनपुट:
long row = 3;
long column = 2;

अपेक्षित आउटपुट:
long expected = 6;

व्याख्या

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

उदाहरण 2
इनपुट:
row = 1
column = 4

अपेक्षित आउटपुट:
expected = 10
इनपुट:
long long row = 1;
long long column = 4;

अपेक्षित आउटपुट:
long long expected = 10;
इनपुट:
long row = 1;
long column = 4;

अपेक्षित आउटपुट:
long expected = 10;

व्याख्या

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

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

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

संकेत 2

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

संकेत 3

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

अपेक्षित जटिलता

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

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।