0
0
DSA Typescriptprogramming~3 mins

Why Search in 2D Matrix in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find a number in a huge grid without looking at every single cell?

The Scenario

Imagine you have a big grid of numbers, like a spreadsheet, and you want to find if a certain number is inside it.

Without any special method, you look at each number one by one, moving row by row.

The Problem

Checking every number takes a lot of time, especially if the grid is huge.

It's easy to get tired, make mistakes, or waste time looking at numbers that don't matter.

The Solution

Using a smart search method, you can skip many numbers and jump closer to the target quickly.

This saves time and effort, making the search fast and easy.

Before vs After
Before
for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[0].length; col++) {
    if (matrix[row][col] === target) return true;
  }
}
return false;
After
let row = 0;
let col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
  if (matrix[row][col] === target) return true;
  else if (matrix[row][col] > target) col--;
  else row++;
}
return false;
What It Enables

This method lets you quickly find if a number exists in a sorted grid without checking every single spot.

Real Life Example

Think of looking for a name in a phone book sorted by last name and first name; you don't check every page but jump closer to the name by comparing.

Key Takeaways

Manual search checks every element, which is slow.

Smart search uses the sorted order to skip parts of the matrix.

This saves time and reduces mistakes.