# LeetCode: Search a 2D Matrix Solution

Flatten into 1D array

## Approach

Flatten 2D into 1D array and do binary search

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}const binarySearch = (arr, target) => {2  let n = arr.length3  let [begin, end] = [0, n - 1]4  let res = -15
6  while (begin <= end) {7    let mid = Math.floor((begin + end) / 2)8
9    if (arr[mid] > target) {10      end = mid - 111    } else if (arr[mid] < target) {12      begin = mid + 113    } else {14      res = mid15      break16    }17  }18
19  return res20}21
22var searchMatrix = function (matrix, target) {23  const arr = matrix.flat()24
25  return binarySearch(arr, target) === -1 ? false : true26}```

Original problem

## Similar problems

Search a 2D Matrix II

leetcode

array

matrix

binary search

## Next Post

LeetCode: Search in Rotated Sorted Array

Sep 12, 2022

Time-boxing and other solutions make life easier

## Previous Post

LeetCode: Path Sum

Sep 10, 2022

Keep subtracting

Search Posts