Day 36 of LeetCoding everyday until I get a J-O-B: Search a 2D Matrix. Today’s secret: The Matrix is fake, and we need to escape it. You are given a grid of numbers and a target. Here is the truth LeetCode doesn't want you to know: If you look at the constraints, the end of one row connects perfectly to the start of the next. It’s not actually a 2D grid. It’s just a single, sorted 1D array that got folded up to intimidate you. The Strategy: The 1D Illusion Because it's technically sorted from top-left to bottom-right, we don't need two binary searches. We just do one. 1. The Bounds: Our pointers are 0 and (ROWS * COLS) - 1. 2. The Math Translation: We find our 1D mid index, but to check the actual value, we have to translate it back to a 2D coordinate: - row = mid // COLS - col = mid % COLS ⚠️ Python Pro-Tip (A Warning): Do NOT name your row variable r if your right pointer is also named r. You will overwrite your boundary, skip your target, and question the validity of your CS degree. Name them row and col. See more: https://lnkd.in/gUki2imQ #LeetCode #Python #BinarySearch #Algorithms #SoftwareEngineering #JobSearch

To view or add a comment, sign in

Explore content categories