![]() |
VOOZH | about |
A number spiral is an infinite grid whose upper-left square has the number 1. The task is to find the number in row Y and column X. Here are the first five layers of the spiral:
Examples:
Input: Y = 2, X = 3
Output: 8
Explanation: The 2nd row, 3rd column contains 8.Input: Y = 4, X = 2
Output: 15
Explanation: The 4th row, 2nd column contains 15.
Approach: To solve the problem, follow the below idea:
It can be observed that grid consists of many squares and the values at boundaries of the square is either in increasing or decreasing order. The answer lies at the boundary of the square whose side is the maximum of Y or X. So now to get the value at Yth row and Xth column we can compute the area of inner square whose side is just one less than the side of square whose boundary contains the answer. The remaining value can be added to the area of inner square by checking the parity of Minimum of Y or X. It can be observed that for even row in the grid, the numbers are in decreasing order, and for the odd row the numbers are in increasing order in the anticlockwise direction.
Step-by-step algorithm:
Below is the implementation of above approach:
8
Time Complexity: O(1)
Auxiliary Space: O(1)