An interactive visualization of how binary search efficiently finds a target in a sorted 2D matrix by treating it as a virtual 1D array.
Binary Search LeetCode 74 ↗ Mediumm x n integer matrix with the following properties:target, return true if target is in the matrix, or false otherwise.fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { val m = matrix.size; val n = matrix[0].size var lo = 0; var hi = m * n - 1 while (lo <= hi) { val mid = (lo + hi) / 2 val row = mid / n; val col = mid % n val v = matrix[row][col] if (v == target) return true else if (v < target) lo = mid + 1 else hi = mid - 1 } return false
Because each row is sorted and the first element of each row is greater than the last element of the previous row, the entire matrix is effectively one long sorted array laid out row by row. We can run standard binary search on this virtual 1D array by converting between flat indices and (row, col) coordinates.
lo = 0, hi = m * n - 1 — the flat indices of the virtual 1D array.mid = (lo + hi) // 2, then map to matrix coordinates: row = mid // n, col = mid % n.matrix[row][col] and compare with the target.True — target found.lo = mid + 1.hi = mid - 1.False.
Standard binary search over m * n elements. The flat-index-to-coordinate mapping is O(1) per iteration,
so the total time is O(log(m * n)) with constant extra space.