![]() |
VOOZH | about |
Given a positive integer n. Consider a matrix of n rows and n columns, in which each element contain absolute difference of its row number and numbers. The task is to calculate sum of each element of the matrix.
Examples :
Input : n = 2 Output : 2 Matrix formed with n = 2 with given constraint: 0 1 1 0 Sum of matrix = 2. Input : n = 3 Output : 8 Matrix formed with n = 3 with given constraint: 0 1 2 1 0 1 2 1 0 Sum of matrix = 8.
Method 1 (Brute Force): Simply construct a matrix of n rows and n columns and initialize each cell with absolute difference of its corresponding row number and column number. Now, find the sum of each cell.
Below is the implementation of above idea :
8
Time Complexity: O(N2), as we are traversing the matrix using nested loops.
Auxiliary Space: O(N2), as we are using extra space for generating and storing the Matrix.
Method 2 (O(n)):
Consider n = 3, matrix formed will be:
0 1 2
1 0 1
2 1 0
Observe, the main diagonal is always 0 since all i are equal to j. The diagonal just above and just below will always be 1 because at each cell either i is 1 greater than j or j is 1 greater than i and so on.
Following the pattern we can see that the total sum of all the elements in the matrix will be, for each i from 0 to n, add i*(n-i)*2.
Below is the implementation of above idea :
8
Time Complexity: O(N), as we are only using single loop to traverse.
Auxiliary Space: O(1), as we are not using any extra space.
Method 3 (Trick):
Consider n = 3, matrix formed will be:
0 1 2
1 0 1
2 1 0
So, sum = 1 + 1 + 1 + 1 + 2 + 2.
On Rearranging, 1 + 2 + 1 + 2 + 2 = 1 + 2 + 1 + 22.
So, in every case we can rearrange the sum of matrix so that the answer always will be sum of first n - 1 natural number and sum of square of first n - 1 natural number.
Sum of first n natural number = ((n)*(n + 1))/2. Sum of first n natural number = ((n)*(n + 1)*(2*n + 1)/6.
Below is the implementation of above idea :
8
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.