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++ code of the above approach #include <bits/stdc++.h> using namespace std;
// To find the index of replaced element 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
}; // if current element is smaller than
// number and next element is greater than
// number then return those indices
}
}
return { m - 1, n - 1 };
} // Driver code int main()
{ vector<vector< int > > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };
// Function call
vector< int > ans = findIndex(arr, 14);
cout << ans[0] << " " << ans[1];
return 0;
} |
// Java code of the above approach import java.util.*;
class GFG {
// To find the index of replaced element
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) {
// if current element is smaller than
// number and next element is greater
// than number then return those indices
return Arrays.asList(i, j);
}
}
}
return Arrays.asList(m - 1 , n - 1 );
}
// Driver code
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 ));
// Function call
List<Integer> ans = findIndex(arr, 14 );
System.out.println(ans.get( 0 ) + " " + ans.get( 1 ));
}
} |
from typing import List
# To find the index of replaced element 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:
# if current element is smaller than
# number and next element is greater
# than number then return those indices
return [i, j]
return [m - 1 , n - 1 ]
# Driver code if __name__ = = '__main__' :
arr = [[ 1 , 1 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
[ 11 , 12 , 13 , 15 , 16 ]]
# Function call
ans = findIndex(arr, 14 )
print (ans[ 0 ], ans[ 1 ])
|
using System;
using System.Collections.Generic;
public class GFG {
// To find the index of replaced element
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 };
}
// if current element is smaller than number
// and next element is greater than number
// then return those indices
}
}
return new List< int >{ m - 1, n - 1 };
}
// Driver Code
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
}
};
// Function call
List< int > ans = FindIndex(arr, 14);
Console.WriteLine(ans[0] + " " + ans[1]);
}
} |
// Javascript code of the above approach // To find the index of replaced element 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]; // if current element is smaller than
// number and next element is greater than
// number then return those indices
}
}
return [m - 1, n - 1];
} // Driver code let arr = [ [1, 1, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 15, 16]
]; // Function call let ans = findIndex(arr, 14); console.log(ans[0] + " " + ans[1]);
|
2 2
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++ code of the above approach #include <bits/stdc++.h> using namespace std;
// To find the index of replaced element 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 loop to do the binary search
while (l <= h) {
// Get the mid element
mid = (l + h) / 2;
// If number itself is found
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 the index of
// replaced element
return { mid / m, mid % m };
} // Driver code int main()
{ vector<vector< int > > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };
// Function call
vector< int > ans = findIndex(arr, 25);
cout << ans[0] << " " << ans[1];
return 0;
} |
// Java code of the above approach import java.util.*;
public class GFG {
// To find the index of replaced element
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 loop to do the binary search
while (l <= h) {
// Get the mid element
mid = (l + h) / 2 ;
// If number itself is found
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 the index of replaced element
return Arrays.asList(mid / m, mid % m);
}
// Driver code
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 ));
// Function call
List<Integer> ans = findIndex(arr, 25 );
System.out.print(ans.get( 0 ) + " " + ans.get( 1 ));
}
} // This code is contributed by Susobhan Akhuli |
# Python code for the above approach: # To find the index of replaced element def findIndex(arr, number):
m = len (arr[ 0 ])
n = len (arr)
l = 0
h = m * n - 1
# While loop to do the binary search
while l < = h:
# Get the mid element
mid = (l + h) / / 2
# If number itself is found
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 the index of
# replaced element
return [mid / / m, mid % m]
# Driver code arr = [[ 1 , 1 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
[ 11 , 12 , 13 , 15 , 16 ]]
# Function call ans = findIndex(arr, 25 )
print (ans[ 0 ], ans[ 1 ])
# This code is contributed by prasad264 |
using System;
using System.Collections.Generic;
public class Gfg {
// To find the index of replaced element
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 loop to do the binary search
while (l <= h) {
// Get the mid element
mid = (l + h) / 2;
// If number itself is found
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 the index of replaced element
return new List< int >() { mid / m, mid % m };
}
// Driver code
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 }
};
// Function call
List< int > ans = findIndex(arr, 25);
Console.WriteLine(ans[0] + " " + ans[1]);
}
} |
// To find the index of replaced element function findIndex(arr, number) {
let l = 0,
m = arr[0].length,
n = arr.length,
mid, x;
let h = m * n - 1;
// While loop to do the binary search
while (l <= h) {
// Get the mid element
mid = Math.floor((l + h) / 2);
x = Math.floor(mid / m);
// If number itself is found
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 the index of
// replaced element
return [x, mid % m];
} // Driver code const arr = [ [1, 1, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 15, 16],
]; // Function call const ans = findIndex(arr, 25); console.log(ans[0] + " " + ans[1]);
//this code is contributed by Tushar Rokade |
2 4
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)