Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Search in Row and Column-wise Sorted Matrix
Optimal Approach using Binary Search



Problem Statement

You are given a 2D matrix where each row and each column is sorted in non-decreasing order. Your task is to search for a given target value in this matrix.

You need to determine whether the target value exists in the matrix or not. Return true if it exists, else return false.

The matrix is not fully sorted overall, but it has a special property:

This property allows us to use an efficient search technique rather than scanning every element.

Examples

MatrixTargetFoundDescription
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
5true5 is present in the middle of the matrix
[[10, 20, 30],
[15, 25, 35],
[27, 29, 37]]
29true29 is present in the last row
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
10false10 is greater than all elements in the matrix
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
0false0 is smaller than all elements in the matrix
[[5]]5trueSingle element match
[[5]]3falseSingle element does not match
[]1falseEmpty matrix has no elements

Solution

To solve this problem efficiently, we take advantage of the matrix's structure—each row and each column is sorted in non-decreasing order.

Understanding the Matrix Structure

Since rows are sorted left-to-right and columns are sorted top-to-bottom, this gives us a clever way to eliminate entire rows or columns at each step. We don’t need to check every cell.

Where to Start?

We begin our search at the top-right corner of the matrix. Why? Because:

  • The element at the top-right is the largest in its row and the smallest in its column.
  • This allows us to move left if the current element is too large or down if the current element is too small.

Step-by-Step Explanation

We set our starting position to row = 0 and col = number_of_columns - 1. Then we enter a loop that continues until either:

  • We find the target (return true), or
  • We move out of bounds (return false)

At each step:

  • If the current element equals the target, we’re done!
  • If the current element is greater than the target, we move left (since all elements to the left are smaller).
  • If the current element is less than the target, we move down (since all elements below are larger).

Handling Edge Cases

  • Empty Matrix: If the matrix has no rows or columns, we return false immediately.
  • Single Element Matrix: If it matches the target, return true. Otherwise, false.
  • Target smaller than all elements: We’ll keep moving left until we exit the matrix.
  • Target greater than all elements: We’ll keep moving down until we exit the matrix.

Why This Works

This approach ensures we only visit at most rows + columns elements in the worst case. So even if the matrix is large, this method stays efficient. The time complexity is O(N + M), where N = number of rows and M = number of columns.

Algorithm Steps

  1. Start at the top-right corner of the matrix, i.e., row = 0, col = M - 1.
  2. While row < N and col ≥ 0:
  3. → If mat[row][col] == target, return true.
  4. → If mat[row][col] > target, move left by doing col--.
  5. → If mat[row][col] < target, move down by doing row++.
  6. If the loop ends without finding the target, return false.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class MatrixSearch {
  public static boolean searchMatrix(int[][] mat, int target) {
    int n = mat.length;
    int m = mat[0].length;
    int row = 0, col = m - 1;

    while (row < n && col >= 0) {
      if (mat[row][col] == target) {
        return true;
      } else if (mat[row][col] > target) {
        col--; // Move left
      } else {
        row++; // Move down
      }
    }
    return false;
  }

  public static void main(String[] args) {
    int[][] mat = {
      {1, 4, 7},
      {2, 5, 8},
      {3, 6, 9}
    };
    int target = 5;
    System.out.println("Element found: " + searchMatrix(mat, target));
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)When the target is found at the starting cell (top-right corner).
Average CaseO(N + M)In each step, we either eliminate a row or a column, leading to at most N + M steps.
Average CaseO(N + M)In the worst case, the search visits one full row and one full column without finding the target.

Space Complexity

O(1)

Explanation: Only a few extra variables are used for row and column tracking, with no additional memory.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M