Given an infinite matrix filled with the natural numbers as shown below:
1 2 4 7 . . . 3 5 8 . . . . 6 9 . . . . . 10 . . . . . . . . . . . .
Also, given an integer N and the task is to find the row and the column of the integer N in the given matrix.
Input: N = 5 Output: 2 2 5 is present in the 2nd row and the 2nd column. Input: N = 3 Output: 2 1
Approach: On observing the problem carefully, the row number can be obtained by subtracting first x natural numbers from N such that they satisfy the condition N – (x * (x + 1)) / 2 ≥ 1 and the resultant value will be the required row number.
To get the corresponding column, add first x natural numbers to 1 such that they satisfy the condition 1 + (y * (y + 1)) / 2 ≤ A. Subtract this resultant value from N to get the gap between the base and the given value and again subtract the gap from y + 1.
Below is the implementation of the above approach:
Time Complexity: O(log(N))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find orientation of a pattern in a matrix
- Print matrix in snake pattern
- Print matrix in diagonal pattern
- Printing string in plus ‘+’ pattern in the matrix
- Print numbers in matrix diagonal pattern
- Print matrix in snake pattern from the last column
- Print concentric rectangular pattern in a 2d matrix
- Rabin-Karp algorithm for Pattern Searching in Matrix
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Find the element at R'th row and C'th column in given a 2D pattern
- Find the maximum sum of Plus shape pattern in a 2-D array
- Find sub-matrix with the given sum
- Find a sub matrix with maximum XOR
- Find if given matrix is Toeplitz or not
- Find the mean vector of a Matrix
- Find row with maximum sum in a Matrix
- Find column with maximum sum in a Matrix
- Find maximum element of each row in a matrix
- Find unique elements in a matrix
- Find a specific pair 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.