VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-number-spiral/

⇱ CSES Solutions - Number Spiral - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Number Spiral

Last Updated : 27 Mar, 2024

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:

👁 NumberSpiral

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.

👁 NumberSpiral2

Step-by-step algorithm:

  • Compare Y and X:
  • If Y>X:
    • Compute the area of inner square which (Y-1)*(Y-1). This represents the numbers which are not on the boundary of the square which contains the answer.
    • Now to add the remaining numbers which are on the boundary, check the parity of Yth row, if the Yth row is odd then simply add X to the area of inner square or else add (2*Y - X) to the area.
  • Else:
    • Similarly, compute the area of inner square which (X-1)*(X-1). This represents the numbers which are not on the boundary of the square which contains the answer.
    • Now to add the remaining numbers which are on the boundary, check the parity of Xth column, if the Xth column is even then simply add Y to the area of inner square or else add (2*X - Y) to the area. This will give the final answer.

Below is the implementation of above approach:


Output
8

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: