You are given an integer ‘N’. Your task is to return a reverse series pattern for the given ‘N’.
The reverse series pattern for ‘N’ = 5 will look like following:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first and only line of each test case contains an integer 'N' denoting the number of rows.
Output format :
For each test case print the integers corresponding to the pattern in the next ‘N’ lines.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 500
Time Limit : 1 sec
2
7
6
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
22 23 24 25 26 27 28
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
2
3
4
1
3 2
4 5 6
1
3 2
4 5 6
10 9 8 7
Observe the pattern of numbers in even and odd rows, can you think of a solution from those observations?
For the given input ‘N’, the pattern contains ‘N’ rows with the ith row containing ‘i’ number of elements, where 1 <= ‘i’ <= ‘N’. The numbers start from 1 and increase up to ‘N’ * (N + 1) / 2. We have to return ‘N’ lines in a specific pattern where the numbers in the odd rows are in increasing order, whereas the numbers in the even rows are in decreasing order.
Algorithm :
O(N^2), where ‘N’ is the number of rows.
As we are returning every character of each line one at a time. The first line contains one character, the second line two, and so on. Hence the time required to return N lines is 1 + 2 + 3 + … + ‘N' = ‘N’ * ('N' + 1) / 2, which is equivalent to O('N' ^ 2).
O(1)
Constant extra space is used.