Update appNew update is available. Click here to update.

Rectangular Numbers

Last Updated: 27 Nov, 2020
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

Ninja has a number ‘N’. He wants to print the pattern in such a way that the outer rectangle is of the number ‘N’ and the number goes on decreasing as we move inside the rectangles.

For example, if ‘N’ = 4, then pattern will be:

4 4 4 4 4 4 4 
4 3 3 3 3 3 4 
4 3 2 2 2 3 4 
4 3 2 1 2 3 4 
4 3 2 2 2 3 4 
4 3 3 3 3 3 4 
4 4 4 4 4 4 4 
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains one integer ‘N’ for the number of rectangles.
Output Format:
For each case, return a 2-d list/array of integers denoting the pattern.

The output of each test case will be printed in a separate line.
Note:
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 100

Time limit: 1 sec.

Approach 1

As we need to move rectangles for each number from N to 1, we start with a loop where N is decreasing after iteration of the loop. Inside the loop, we basically only need to choose the location of the border elements. So we can run a nested loop as we travel in the case of a 2D array and whenever we stand at the border indexes, we need to put the number in that index.

 

Algorithm:

 

  • Declare and Initialize size as 2 * ‘n’ - 1.
  • Declare and Initialize front as ‘0’ and back as ‘size’ - 1
  • Declare a 2D-array ‘arr’ with row and column as ‘size’
  • Run a while loop from ‘n’ to 0.
    • Run a for loop ‘i’ = ‘front’ to ‘back’
      • Run a for loop ‘i’ = ‘front’ to ‘back’
        • If ‘i’ or ‘j’ is either equal to ‘front’ or ‘back’.
          • Then arr[i][j] = ‘n’
    • Increase ‘front’ by 1
    • Decrease ‘back’ by 1
    • Decrease ‘n’ by 1
  • Return 2D array.
Try Problem