Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the target is equal to the current matrix element.
DSA Java
if(matrix[i][j] [1] target) { return true; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '==' causes assignment, not comparison.
Using '!=' will check for inequality, which is not what we want here.
✗ Incorrect
Use '==' to compare values in Java. '=' is for assignment.
2fill in blank
mediumComplete the code to move to the next row when the target is greater than the last element in the current row.
DSA Java
if(target > matrix[i][matrix[i].[1] - 1]) { i++; j = 0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length()' which is for Strings, not arrays.
Using 'size' which is for collections, not arrays.
✗ Incorrect
Use 'length' to get the number of columns in a 2D array in Java.
3fill in blank
hardFix the error in the loop condition to iterate over all rows of the matrix.
DSA Java
for(int i = 0; i [1] matrix.length; i++) { // loop body }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' or '>' will not start the loop correctly.
Using '<=' causes the loop to run one extra time.
✗ Incorrect
Use '<' to iterate from 0 up to but not including matrix.length.
4fill in blank
hardFill both blanks to correctly implement binary search on a sorted row.
DSA Java
int left = 0, right = matrix[[1]].[2] - 1; while(left <= right) { int mid = left + (right - left) / 2; if(matrix[row][mid] == target) return true; else if(matrix[row][mid] < target) left = mid + 1; else right = mid - 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length()' or 'size' which are invalid for arrays.
Using wrong variable instead of 'row' for the row index.
✗ Incorrect
Use 'row' as the index for the current row and 'length' to get the number of columns.
5fill in blank
hardFill both blanks to complete the method that searches the matrix for the target using binary search on each row.
DSA Java
public boolean searchMatrix(int[][] matrix, int target) {
for(int [1] = 0; [1] < matrix.length; [1]++) {
int left = 0, right = matrix[[1]].[2] - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(matrix[[1]][mid] == target) return true;
else if(matrix[[1]][mid] < target) left = mid + 1;
else right = mid - 1;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'j' as loop variable for rows is confusing.
Using 'length()' or 'size' instead of 'length' for arrays.
✗ Incorrect
Use 'i' as the loop variable and row index, and 'length' to get the number of columns.
