1. Linear Scan (Brute Force)
Intuition
Iterate across all m rows and n columns. If matrix[r][c] == target, return true. If traversal completes without matching, return false.
When to apply: Use to understand matrix dimensions and baseline membership check.
Linear Matrix Scan Trace
2 of 2 questions left todayMatrix 3x4: row 0 is [1, 3, 5, 7]
Matrix 3x4: row 0 is [1, 3, 5, 7]. Target = 3. Check (0,0)=1.
public class Main { public static class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) return false; int m = matrix.length, n = matrix[0].length; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { if (matrix[r][c] == target) return true; } } return false; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] matrix = { {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60} }; int target = 3; System.out.println("Found target 3: " + sol.searchMatrix(matrix, target)); }}Time & Space Complexity
- Time complexity:
O(m * n)— Worst-case scans all m*n elements. - Space complexity:
O(1)— O(1) memory.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.