Search Sorted Matrix Solution in C++

Search Sorted Matrix Solution in C++

Featured Summary: Searching a sorted 2D matrix efficiently in C++ involves leveraging binary search techniques. By identifying the correct row using the matrix's boundaries, and subsequently running a binary search on that targeted row, developers can achieve an optimal runtime complexity of O(log R + log C). This eliminates the need for naive O(R * C) traversal, drastically improving search speeds for large datasets.

Understanding the Row-Column Sorted Matrix Problem

In this comprehensive software engineering tutorial, we deeply explore a highly optimized C++ solution to search for a specific value within a strictly row-column sorted matrix. In algorithm design, matrices often represent complex data grids. When these grids are sorted, we can exploit their mathematical properties to perform extremely fast searches.

In modern software development, data retrieval efficiency is paramount. When dealing with millions of records stored in a tabular format, linear search algorithms quickly become a bottleneck. By ensuring that our 2D data grids are properly sorted during insertion, we unlock the ability to utilize binary search variations. This specific problem is frequently asked in technical interviews at top-tier technology companies, testing a candidate's ability to abstract a 2D geometry into a 1D sequence logically without physically copying data into a new array. Our approach perfectly balances theoretical performance with practical memory safety.

The core constraints of our sorted matrix state that each row is sorted in strictly ascending order from left to right. Furthermore, the first element of any given row is strictly greater than or equal to the very last element of the preceding row. This exact property guarantees that the entire 2D structure mathematically behaves identically to a contiguous, sorted 1D array when traversed sequentially. This allows us to transition from linear time sequential scanning to logarithmic time searching, a crucial performance boost for enterprise applications and large-scale data processing.

Visual representation of a sorted 2D matrix binary search algorithm implemented in C++

Detailed Algorithm Steps

To master this problem, one must understand the two primary phases of the search mechanism. Rather than iterating through every single integer, we aggressively prune our search space.

  • Row Selection Phase: Since the entire matrix behaves like a flattened sorted array, our first objective is to identify exactly which row the target number could possibly reside in. The target x must logically fall between the first (minimum) and last (maximum) element of a specific row. Thus, we check the condition: mat[i][0] <= x && mat[i][cols-1] >= x. By scanning the boundaries of the rows, or even binary searching the first column, we swiftly eliminate rows that mathematically cannot contain our target.
  • Binary Search Phase: Once the single candidate target row is discovered, the problem dramatically simplifies. We extract that specific row, which is essentially a standard, sorted 1D array. We then execute a standard binary search algorithm strictly on that row to find the target integer. If the binary search returns true, the element exists. If it terminates without a match, the element is definitively absent from the matrix.

Complete and Optimized C++ Implementation

Below is the fully optimized C++ implementation for this algorithm. This code heavily utilizes modern C++ features such as vectors and lambda functions to maintain clean, readable, and highly efficient execution paths.


#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool searchMatrix(vector<vector<int>> &mat, int x) {
        vector<int>*row = nullptr;
        int rows = mat.size();
        if (rows == 0) return false;
        int cols = mat[0].size();
        if (cols == 0) return false;
        
        // Phase 1: Rapidly locate the candidate row
        for( int i = 0; i < rows; i++ ){
            if( mat[i][0] <= x && mat[i][cols-1] >= x ){
                row = &(mat[i]);
                break;
            }
        }
        
        // If no valid row contains the target range, it does not exist
        if( row == nullptr ) return false;
        
        // Phase 2: Execute Binary Search within the candidate row
        auto binarySearch = [row, x]( int low, int high ) -> bool{
            while( low <= high ){
                int mid = low + (high-low)/2;
                if( (*row)[mid] == x ){
                    return true;
                } else if((*row)[mid] < x ){
                    low =  mid + 1;
                } else {
                    high = mid - 1;
                }
            }
            return false;
        };   
        
        return binarySearch(0, cols - 1 );
    }
};

Algorithmic Complexity and Performance Analysis

A true software engineer always evaluates the computational complexity of their code. Let us break down the performance footprint of our C++ solution.

  • Time Complexity Analysis: The current time complexity stands at O(R + log C), where R is the total number of rows and C is the total number of columns. The initial row discovery involves a linear scan taking O(R) time. The subsequent binary search operates in O(log C) time. For extreme optimizations, developers can upgrade the row selection phase to use binary search as well, driving the theoretical time complexity down to a pure O(log R + log C) or equivalently O(log(R * C)).
  • Space Complexity Analysis: The space complexity is an exceptionally optimal O(1) auxiliary space. Since we simply pass references and pointers to the existing matrix in memory, we do not instantiate any duplicate data structures. This constant space consumption makes the algorithm perfectly suited for severely memory-constrained environments and embedded systems.

Frequently Asked Questions (FAQ)

What is the time complexity of searching a sorted 2D matrix?

The optimal time complexity is O(log R + log C), where R is the number of rows and C is the number of columns. This is achieved by performing binary search twice: once to find the row and once to find the element.

Can we flatten the 2D matrix into a 1D array to search it?

Yes, mathematically treating the matrix as a flattened 1D array and performing a single holistic binary search evaluates to O(log(R * C)) time, which identically simplifies to O(log R + log C). This offers the exact same optimal runtime scaling.

Why use C++ for algorithm design?

C++ provides unparalleled low-level memory management and execution speed. Its Standard Template Library (STL) allows engineers to implement complex routines with minimal runtime overhead, making it the premier language for competitive programming and performance-critical systems.