Leetcode 74: Search a 2D Matrix

grid47
grid47
Exploring patterns and algorithms
Oct 30, 2024 5 min read

A soft, glowing grid with a pinpoint highlighting the search area.
Solution to LeetCode 74: Search a 2D Matrix Problem

You are given an m x n matrix where each row is sorted in non-decreasing order, and the first integer of each row is greater than the last integer of the previous row. Given a target integer, return true if the target exists in the matrix or false otherwise. The solution must have a time complexity of O(log(m * n)).
Problem
Approach
Steps
Complexity
Input: You are given a matrix of size m x n with sorted rows and specific order between consecutive rows.
Example: matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]], target = 10
Constraints:
• 1 <= m, n <= 100
• -104 <= matrix[i][j], target <= 104
Output: Return true if the target is present in the matrix; otherwise, return false.
Example: true
Constraints:
• The function should return a boolean value indicating the presence of the target in the matrix.
Goal: Efficiently search for the target in the matrix using binary search.
Steps:
• Flatten the matrix into a 1D array (conceptually).
• Use binary search to check if the target exists within the range of the flattened matrix.
Goal: Constraints on the matrix dimensions and target value.
Steps:
• 1 <= m, n <= 100
• -104 <= matrix[i][j], target <= 104
Assumptions:
• The matrix has at least one element.
• Matrix rows and columns are sorted in non-decreasing order, and no elements are repeated across rows.
Input: matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]], target = 10
Explanation: The target 10 is present at the second row and second column, so the answer is true.

Input: matrix = [[1, 5, 9], [11, 13, 15], [17, 19, 21]], target = 8
Explanation: The target 8 is not present in the matrix, so the answer is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus