-2

question : Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.

Ans : the solution given is correct but when element variable is updated at different location it gives error and I can't understand why?

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int trow = matrix.size();
    int tcol = matrix[0].size();

    int rowIndex = 0;
    int colIndex = tcol - 1;
    
    int element = matrix[rowIndex][colIndex]; // already defined here
    while(rowIndex < trow && colIndex >= 0){
        element = matrix[rowIndex][colIndex]; // works here
        if(element == target){
            return 1;
        }
        if(element > target){
            colIndex --;
        }
        if(element < target){
            rowIndex ++;
        }
       // element = matrix[rowIndex][colIndex]; // this gives error here
    }
    return 0;
}
};
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • as element is already defined outside while loop updating it after all conditions are checked should be fine but gives error in leetcode. – Ankush Makkar Jul 14 '23 at 13:07
  • 1
    The second position is *after* the indices are updated. Are they still in bounds? BTW, have you already studied the binary search algorithm? – Bob__ Jul 14 '23 at 13:13
  • 1
    Can you provide a [mcve] with `main` function, hardcoded input data and expected output? – jabaa Jul 14 '23 at 13:14
  • Have you stepped through an example where `target` is not within your matrix? Try `matrix=[[1]]`, `target=2`. What's the state on the line that gives an error? – wLui155 Jul 14 '23 at 13:29
  • Looks like you are not learning c++ from a good source. Good sources to learn cpp from are : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date with the latest guidelines. – Pepijn Kramer Jul 14 '23 at 14:01
  • *"it gives error"* -- what's the error? Compile-time? Run-time? Is there a message? For a runtime error: at which line, and what are the values of the variables used in that line? – JaMiT Jul 14 '23 at 23:21

1 Answers1

0

when element variable is updated at different location it gives error and I can't understand why?

Your while loop condition ensures that at the start of the loop body, the indices rowIndex and colIndex are within the array bounds.

However, during the execution of the loop's body, one of these variables is updated with either colIndex--; or rowIndex++;. Once that has happened you cannot be sure the updated value is still within bounds, and so it is unsafe to use them at the end of the loop body to access matrix[rowIndex][colIndex]. First the loop condition should be verified, and only if it is true, it is safe again to access matrix[rowIndex][colIndex].

If you access it at the end of the loop's body, it will go wrong when the matrix does not have the target value.

The most simple example is an array with just one row and column (so trow and tcol are both 1). Let's say matrix[0][0] is 10, and the target value is 5. Then the loop will start with rowIndex and colIndex both equal to 0. element will be 10. The comparison element > target is true, so colIndex is updated to become -1. Now it would be wrong to access matrix[rowIndex][colIndex] as -1 is not a valid index. Instead the while condition should be evaluated first, which would be false, and the function would return 0 (i.e., target was not found).

That's why the retrieval of matrix[rowIndex][colIndex] needs to happen at the top of the loop body and not at the bottom of it.

trincot
  • 317,000
  • 35
  • 244
  • 286