Find indices in a sorted Matrix where a new number can be replaced
Last Updated :
25 Jul, 2023
Given a matrix arr[][] which is sorted by the increasing number of elements and a number X, the task is to find the position where the input integer can be replaced with an existing element without disturbing the order of the sorted elements. The matrix is sorted in such a manner that:
- Every row is sorted in increasing order of elements.
- Every single element in the current row will be greater than every single element of the previous row and smaller than every single element of the next row.
Examples:
Input: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X = 2
Output: 0 2
Explanation: In the given matrix, X = 2 so 2 can be replaced either with {0, 1} or {0, 2} because replacement at these two positions does not break the order of the sorted matrix.
Input: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X = 14
Output: 2 2
Explanation: The input number is 14 so it could be either replaced with 13 or 15 to maintain the sorted order.
Brute Force Approach : The idea is to use the concept of Linear Search by completely traversing over the input matrix for finding required indices .
Steps involved in the implementation of code:
- Initialize two variables m = arr.size() and n = arr[0].size() and start iterating over the matrix and for every single iteration repeat the below mentioned steps .
- Check whether the current element is smaller than or equal to the number and the next element is greater than or equal to the number.
- If both conditions are true then return current indices.
- If the entire matrix is covered and indices are not found then return m-1 and n-1 as this will be the place for replacement .
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > findIndex(vector<vector< int > > arr, int number)
{
int m = arr.size(), n = arr[0].size();
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < n - 1; j++) {
if (arr[i][j] <= number
&& arr[i][j + 1] >= number)
return {
i, j
};
}
}
return { m - 1, n - 1 };
}
int main()
{
vector<vector< int > > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };
vector< int > ans = findIndex(arr, 14);
cout << ans[0] << " " << ans[1];
return 0;
}
|
Java
import java.util.*;
class GFG {
static List<Integer> findIndex(List<List<Integer> > arr,
int number)
{
int m = arr.size(), n = arr.get( 0 ).size();
for ( int i = 0 ; i < m; i++) {
for ( int j = 0 ; j < n - 1 ; j++) {
if (arr.get(i).get(j) <= number
&& arr.get(i).get(j + 1 ) >= number) {
return Arrays.asList(i, j);
}
}
}
return Arrays.asList(m - 1 , n - 1 );
}
public static void main(String[] args)
{
List<List<Integer> > arr = Arrays.asList(
Arrays.asList( 1 , 1 , 3 , 4 , 5 ),
Arrays.asList( 6 , 7 , 8 , 9 , 10 ),
Arrays.asList( 11 , 12 , 13 , 15 , 16 ));
List<Integer> ans = findIndex(arr, 14 );
System.out.println(ans.get( 0 ) + " " + ans.get( 1 ));
}
}
|
Python3
from typing import List
def findIndex(arr: List [ List [ int ]], number: int ) - > List [ int ]:
m, n = len (arr), len (arr[ 0 ])
for i in range (m):
for j in range (n - 1 ):
if arr[i][j] < = number and arr[i][j + 1 ] > = number:
return [i, j]
return [m - 1 , n - 1 ]
if __name__ = = '__main__' :
arr = [[ 1 , 1 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
[ 11 , 12 , 13 , 15 , 16 ]]
ans = findIndex(arr, 14 )
print (ans[ 0 ], ans[ 1 ])
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static List< int > FindIndex(List<List< int > > arr,
int number)
{
int m = arr.Count;
int n = arr[0].Count;
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < n - 1; j++) {
if (arr[i][j] <= number
&& arr[i][j + 1] >= number) {
return new List< int >{ i, j };
}
}
}
return new List< int >{ m - 1, n - 1 };
}
static public void Main()
{
List<List< int > > arr = new List<List< int > >() {
new List< int >{ 1, 1, 3, 4, 5 },
new List< int >{ 6, 7, 8, 9, 10 },
new List< int >
{
11, 12, 13, 15, 16
}
};
List< int > ans = FindIndex(arr, 14);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
|
Javascript
function findIndex(arr, number) {
let m = arr.length;
let n = arr[0].length;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n - 1; j++) {
if (arr[i][j] <= number && arr[i][j + 1] >= number)
return [i, j];
}
}
return [m - 1, n - 1];
}
let arr = [
[1, 1, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 15, 16]
];
let ans = findIndex(arr, 14);
console.log(ans[0] + " " + ans[1]);
|
Time Complexity: O(M*N), Where M is the number of rows and N is the number of columns in the matrix
Auxiliary Space: O(1)
Optimal Approach: This can be solved with the following idea:
The approach is to apply the binary search for the optimal solution.
Steps involved in the implementation of code:
- Initialize l(low) as 0 and h(high) as (m*n)-1. Apply binary search using a while loop where l < h.
- Initialize mid(middle) as (l+h)/2 and access the middle element using arr[mid/m][mid%m] .
- Once the binary search’s loop is over then return the indexes which are represented by mid.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > findIndex(vector<vector< int > > arr, int number)
{
int l = 0, m = arr[0].size(), n = arr.size(), mid;
int h = m * n - 1;
while (l <= h) {
mid = (l + h) / 2;
if (arr[mid / m][mid % m] == number) {
return { mid / m, mid % m };
}
else if (arr[mid / m][mid % m] < number) {
l = mid + 1;
}
else {
h = mid - 1;
}
}
return { mid / m, mid % m };
}
int main()
{
vector<vector< int > > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };
vector< int > ans = findIndex(arr, 25);
cout << ans[0] << " " << ans[1];
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static List<Integer>
findIndex(List<List<Integer> > arr, int number)
{
int l = 0 , m = arr.get( 0 ).size(), n = arr.size(),
mid = 0 ;
int h = m * n - 1 ;
while (l <= h) {
mid = (l + h) / 2 ;
if (arr.get(mid / m).get(mid % m) == number) {
return Arrays.asList(mid / m, mid % m);
}
else if (arr.get(mid / m).get(mid % m)
< number) {
l = mid + 1 ;
}
else {
h = mid - 1 ;
}
}
return Arrays.asList(mid / m, mid % m);
}
public static void main(String[] args)
{
List<List<Integer> > arr = Arrays.asList(
Arrays.asList( 1 , 1 , 3 , 4 , 5 ),
Arrays.asList( 6 , 7 , 8 , 9 , 10 ),
Arrays.asList( 11 , 12 , 13 , 15 , 16 ));
List<Integer> ans = findIndex(arr, 25 );
System.out.print(ans.get( 0 ) + " " + ans.get( 1 ));
}
}
|
Python3
def findIndex(arr, number):
m = len (arr[ 0 ])
n = len (arr)
l = 0
h = m * n - 1
while l < = h:
mid = (l + h) / / 2
if arr[mid / / m][mid % m] = = number:
return [mid / / m, mid % m]
elif arr[mid / / m][mid % m] < number:
l = mid + 1
else :
h = mid - 1
return [mid / / m, mid % m]
arr = [[ 1 , 1 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
[ 11 , 12 , 13 , 15 , 16 ]]
ans = findIndex(arr, 25 )
print (ans[ 0 ], ans[ 1 ])
|
C#
using System;
using System.Collections.Generic;
public class Gfg {
static List< int > findIndex(List<List< int > > arr,
int number)
{
int l = 0, m = arr[0].Count, n = arr.Count, mid = 0;
int h = m * n - 1;
while (l <= h) {
mid = (l + h) / 2;
if (arr[mid / m][mid % m] == number) {
return new List< int >() { mid / m, mid % m };
}
else if (arr[mid / m][mid % m] < number) {
l = mid + 1;
}
else {
h = mid - 1;
}
}
return new List< int >() { mid / m, mid % m };
}
static void Main( string [] args)
{
List<List< int > > arr = new List<List< int > >() {
new List< int >() { 1, 1, 3, 4, 5 },
new List< int >() { 6, 7, 8, 9, 10 },
new List< int >() { 11, 12, 13, 15, 16 }
};
List< int > ans = findIndex(arr, 25);
Console.WriteLine(ans[0] + " " + ans[1]);
}
}
|
Javascript
function findIndex(arr, number) {
let l = 0,
m = arr[0].length,
n = arr.length,
mid, x;
let h = m * n - 1;
while (l <= h) {
mid = Math.floor((l + h) / 2);
x = Math.floor(mid / m);
if (arr[x][mid % m] == number) {
return [x, mid % m];
} else if (arr[x][mid % m] < number) {
l = mid + 1;
} else {
h = mid - 1;
}
}
return [x, mid % m];
}
const arr = [
[1, 1, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 15, 16],
];
const ans = findIndex(arr, 25);
console.log(ans[0] + " " + ans[1]);
|
Time Complexity: O(log(mn)), where m is the number of rows and n is the number of columns in input vector.
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...