Sunday, February 26, 2023
HomeSoftware DevelopmentDiscover indices in a sorted Matrix the place a brand new quantity...

# Discover indices in a sorted Matrix the place a brand new quantity will be changed

Given a matrix arr[][] which is sorted by the rising variety of components and a quantity X, the duty is to search out the place the place the enter integer will be changed with an present ingredient with out disturbing the order of the sorted components. The matrix is sorted in such a way that:

• Each row is sorted in rising order of components.
• Each single ingredient within the present row will likely be better than each single ingredient of the earlier row and smaller than each single ingredient of the following row.

Examples:

Enter: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X = Â 2
Output: 0 2
Rationalization: Within the given matrix, X = 2 so 2 will be changed both with {0, 1} or {0, 2} as a result of alternative at these two positions doesn’t break the order of the sorted matrix.

Enter: arr[][] = { {1, 1, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 15, 16} }, X = 14
Output: 2 2
Rationalization: The enter quantity is 14 so it may very well be both changed with 13 or 15 to keep up the sorted order.

Method: This may be solved with the next concept:

The strategy is to use the binary search for the optimum answer.

Â Steps concerned within the implementation of code:

• Initialize l(low) as 0 and h(excessive) as (m*n)-1. Apply binary search utilizing a whereas loop the place l < h.
• Initialize mid(center) as (l+h)/2 Â and entry the center ingredient utilizing arr[mid/m][mid%m] .
• As soon as the binary searchâ€™s loop is over then return the indexes that are represented by mid.

Under is the implementation of the above strategy:

## C++

```// C++ code of the above strategy
#embrace <bits/stdc++.h>
utilizing namespace std;

// To seek out the index of changed ingredient
vector<int> findIndex(vector<vector<int> > arr, int quantity)
{

int l = 0, m = arr[0].measurement(), n = arr.measurement(), mid;
int h = m * n - 1;

// Whereas loop to do the binary search
whereas (l <= h) {

// Get the mid ingredient
mid = (l + h) / 2;

// If quantity itself is discovered
if (arr[mid / m][mid % m] == quantity) {
return { mid / m, mid % m };
}

else if (arr[mid / m][mid % m] < quantity) {
l = mid + 1;
}

else {
h = mid - 1;
}
}

// Return the index of
// changed ingredient
return { mid / m, mid % m };
}

// Driver code
int fundamental()
{
vector<vector<int> > arr = { { 1, 1, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 15, 16 } };

// Perform name
vector<int> ans = findIndex(arr, 25);
cout << ans[0] << " " << ans[1];

return 0;
}```

Time Complexity: O(logN)
Auxiliary House: O(1)Â

RELATED ARTICLES