![]() |
VOOZH | about |
Given an integer n, create a square pattern of size n x n such that the edges of the pattern contain the numbers 1 to n in ascending order on the top and left edges, and n to 1 in descending order on the bottom and right edges. The remaining elements of the pattern should be filled with numbers that are equal to the absolute difference between their row and column index plus 2. The resulting pattern should be returned as a 2 - dimensional list.
Examples:
Input: 3
Output:
1 2 3
2 3 2
3 2 1Input: 4
Output:
1 2 3 4
2 3 4 3
3 4 3 2
4 3 2 1
Approach: Follow the steps below to solve the problem:
Below is the implementation for the above approach:
1 2 3 4 2 3 4 3 3 4 3 2 4 3 2 1
Time complexity: O(n^2), where n is the size of the pattern. This is because the program uses two nested for loops to iterate over the n rows and n columns of the pattern, resulting in a total of n^2 iterations.
Auxiliary Space: O(1), because it only uses a few variables to store intermediate values and the memory usage does not depend on the size of the input. The variables used in the program are n, i, and j all of which have a constant size regardless of the size of the input.