1. Exhaustive Linear Scan
Intuition
Check all M x N elements without exploiting any sorted order.
Algorithm
- Step 1: Iterate row r from 0 to m - 1.
- Step 2: Iterate col c from 0 to n - 1.
- Step 3: If matrix[r][c] == target, return true.
- Step 4: If traversal completes without match, return false.
Exhaustive Linear Scan Trace
2 of 2 questions left todayStart linear scan at top-left cell (0,0)
Start linear scan at top-left cell (0,0). Value is 1, target is 5. 1 != 5.
#include <iostream>#include <vector> class Solution {public: bool searchMatrix(const std::vector<std::vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int m = matrix.size(), n = matrix[0].size(); for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { if (matrix[r][c] == target) return true; } } return false; }}; int main() { Solution solver; std::vector<std::vector<int>> 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} }; std::cout << (solver.searchMatrix(matrix, 5) ? "true" : "false") << std::endl; std::cout << (solver.searchMatrix(matrix, 20) ? "true" : "false") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(M * N)— Time complexity for Exhaustive Linear Scan. - Space complexity:
O(1)— Space complexity for Exhaustive Linear Scan.
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.