Search a 2D matrix II Leetcode Solution

Search a 2D matrix II Leetcode Problem :

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.
jump game leetcode

Search a 2D Matrix || Leetcode Solution :

Constraints :

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -109 <= matrix[i][j] <= 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 <= target <= 109

Example 1:

  • Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
  • Output: false

Intuition :

Traversing using corner elemnts;

Approach :

  1. first choose the corner (either top right or bottom left)….i have chosen bottom left
  2. Traverse till opposite corner is reaches..
  3. a) if corner element is equal to target ….return true;
    b) if target is smaller than corner elemnt….then the target must be abbove the bottom row…..so bottom row–;
    c) if target is greater than corner elemnt….then the target must be on the rigth of left column…..so left column++;
  4. if loop completes means no element found so return false.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription