Given a 2D array of size M x N. Calculate count of positions in 2D array where address as per row major order equals to address as per column major order.
Input : 3 5
Output : 3
Row major address is same as column major for following i, j
pairs (1, 1), (2, 3) & (3, 5)
Input : 4 4
Output : 4
Lets consider element with index i, j
Row major address = B + w * (N * (i-1) + j-1) Column major address = B + w * (M * (j-1) + i-1)
B : Base address of the array
w : Size of each element of the array
Equating both addresses, we get B + w * (N * (i-1) + j-1) = B + w * (M * (j-1) + i-1) N * (i-1) + j = M * (j-1) + i N*i - N + j = M*j - M + i M*j - j = N*i - N + M - i (M-1) * j = N*i - N + M - i j = (N*i - N + M - i)/(M-1) - (Eq. 1) Similarly i = (M*j - M + N - j)/(N-1) - (Eq. 2)
Now we have established a relation between i and j
Iterate for all possible i and find corresponding j If j comes out to be an integer in the range 1 to N, increment the counter.
Below is the implementation of above approach.
Time Complexity: O(M)
Complexity can be reduced to O(min(M, N)) by establishing relation of i in terms of j(Eq. 2) and iterating for all possible j in case N<M and by establishing relation j in terms of i(Eq. 1) and iterating for all possible i otherwise.
- Performance analysis of Row major and Column major order of storing arrays in C
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Search in a sorted 2D matrix (Stored in row major order)
- Swap major and minor diagonals of a square matrix
- Print all elements in sorted order from row and column wise sorted matrix
- heapq in Python to print all elements in sorted order from row and column wise sorted matrix
- Number of pair of positions in matrix which are not accessible
- Count the number of pairs that have column sum greater than row sum
- Count number of islands where every island is row-wise and column-wise separated
- Print number in ascending order which contains 1, 2 and 3 in their digits.
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sorting rows of matrix in descending order followed by columns in ascending order
- Find a way to fill matrix with 1's and 0's in blank positions
- Minimum cost to cover the given positions in a N*M grid
- Sum of middle row and column in Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : vt_m