Software Development

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

Discover indices in a sorted Matrix the place a brand new quantity may be changed
Written by admin


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

  • Each row is sorted in growing order of parts.
  • Each single component within the present row can be larger than each single component of the earlier row and smaller than each single component 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
Clarification: Within the given matrix, X = 2 so 2 may 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
Clarification: The enter quantity is 14 so it might be both changed with 13 or 15 to take care of the sorted order.

Strategy: This may be solved with the next concept:

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

 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 component 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.

Beneath is the implementation of the above strategy:

C++

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

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

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

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

        // Get the mid component
        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 component
    return { mid / m, mid % m };
}

// Driver code
int important()
{
    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) 

About the author

admin

Leave a Comment