Bird
Raised Fist0
DSA Javascriptprogramming~15 mins

Search in 2D Matrix in DSA Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Search in 2D Matrix
What is it?
Searching in a 2D matrix means finding whether a specific number or value exists inside a grid of rows and columns. The matrix is like a table with numbers arranged in rows and columns. We want to quickly check if the number is there and where it is. This helps in many real-world problems like maps, images, or spreadsheets.
Why it matters
Without efficient search in a 2D matrix, finding a number would take a long time, especially if the matrix is large. This would slow down programs and make tasks like image processing or data lookup frustrating. Efficient search saves time and computing power, making software faster and more responsive.
Where it fits
Before learning this, you should understand basic arrays and how to search in a simple list. After this, you can learn about more complex data structures like trees or graphs and algorithms like binary search in higher dimensions.
Mental Model
Core Idea
Searching in a 2D matrix is like looking for a book in a library where shelves and rows are sorted, so you can skip many books at once instead of checking one by one.
Think of it like...
Imagine a phone book organized by last names in alphabetical order on each page, and pages themselves are sorted. To find a name, you don't check every name but jump to the right page and then scan the list. The 2D matrix search uses a similar idea to jump quickly to the right area.
Matrix (rows and columns):
┌─────────────┐
│ 1  3  5  7  │
│ 8  10 12 15 │
│ 16 18 20 22 │
│ 23 25 27 30 │
└─────────────┘
Search path example:
Start at top-right (7), if target < 7 go left, else go down.
Moves: 7 -> 15 -> 12 -> found 12
Build-Up - 6 Steps
1
FoundationUnderstanding 2D Matrix Structure
🤔
Concept: Learn what a 2D matrix is and how data is arranged in rows and columns.
A 2D matrix is like a grid with rows and columns. Each cell holds a value. For example, a 3x3 matrix has 3 rows and 3 columns. You can access elements by row and column indexes, like matrix[row][column].
Result
You can visualize and access any element in the matrix by its row and column numbers.
Understanding the layout of data in rows and columns is essential before searching because it defines how you move through the matrix.
2
FoundationSimple Linear Search in 2D Matrix
🤔
Concept: Searching every element one by one to find the target value.
Check each row from top to bottom, and inside each row, check each column from left to right. If the element matches the target, return true; otherwise, continue until all elements are checked.
Result
If the target is in the matrix, it will be found; otherwise, the search ends after checking all elements.
This method works but is slow for large matrices because it checks every element without skipping any.
3
IntermediateUsing Sorted Rows and Columns for Faster Search
🤔
Concept: If rows and columns are sorted, we can skip parts of the matrix to find the target faster.
When each row is sorted left to right and each column is sorted top to bottom, start searching from the top-right corner. If the target is smaller than the current element, move left; if larger, move down. Repeat until found or out of bounds.
Result
The search takes fewer steps, often much faster than checking every element.
Knowing the matrix is sorted in both directions allows us to eliminate whole rows or columns at each step, speeding up the search.
4
IntermediateImplementing Efficient Search Algorithm in JavaScript
🤔Before reading on: do you think starting from the top-right or bottom-left corner is better for this search? Commit to your answer.
Concept: Write code to perform the efficient search using the top-right corner approach.
function searchMatrix(matrix, target) { 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; } // Example usage: // matrix = [[1,3,5,7],[8,10,12,15],[16,18,20,22],[23,25,27,30]] // target = 12 // returns true
Result
The function returns true if the target is found, false otherwise.
Implementing the algorithm helps solidify the logic of moving left or down based on comparisons, making the search efficient.
5
AdvancedBinary Search on Each Row for Target
🤔Before reading on: do you think binary search on each row is faster or the top-right corner method? Commit to your answer.
Concept: Use binary search on each row separately because rows are sorted, but columns may not be fully sorted.
For each row, perform binary search: - Set low = 0, high = number of columns - 1 - While low <= high: - mid = Math.floor((low + high) / 2) - If matrix[row][mid] == target, return true - Else if matrix[row][mid] < target, low = mid + 1 - Else high = mid - 1 If no row contains target, return false.
Result
This method has time complexity O(rows * log(columns)) and works well if only rows are sorted.
Knowing when to use binary search on rows versus the top-right corner method depends on matrix sorting properties.
6
ExpertHandling Unsorted or Partially Sorted Matrices
🤔Before reading on: do you think the efficient search method works if the matrix is not sorted? Commit to your answer.
Concept: When the matrix is not sorted, efficient search methods fail; we must use other strategies like linear search or advanced data structures.
If the matrix is unsorted, no shortcuts exist. You must check every element. Alternatively, preprocess the matrix into a searchable structure like a hash map or balanced tree for faster queries later.
Result
Without sorting, search time increases to O(rows * columns) unless preprocessing is done.
Understanding the limits of sorting assumptions prevents wrong algorithm choices and guides when to preprocess data.
Under the Hood
The efficient search exploits the sorted order of rows and columns. Starting at the top-right corner, each comparison eliminates either a whole row or a whole column from consideration. This works because if the current number is bigger than the target, all numbers below in that column are bigger, so we move left. If smaller, all numbers to the left in that row are smaller, so we move down. This step-by-step elimination reduces the search space quickly.
Why designed this way?
This method was designed to improve over brute force search by using the matrix's sorted properties. It balances simplicity and efficiency without complex data structures. Alternatives like binary search on each row exist but may be slower if the matrix is large. The top-right corner approach is intuitive and easy to implement.
Start at top-right:
┌─────┬─────┬─────┬─────┐
│  1  │  3  │  5  │  7  │
├─────┼─────┼─────┼─────┤
│  8  │ 10  │ 12  │ 15  │
├─────┼─────┼─────┼─────┤
│ 16  │ 18  │ 20  │ 22  │
├─────┼─────┼─────┼─────┤
│ 23  │ 25  │ 27  │ 30  │
└─────┴─────┴─────┴─────┘
Compare target with current:
If target < current: move left
If target > current: move down
Repeat until found or out of bounds
Myth Busters - 3 Common Misconceptions
Quick: Does the efficient search method work if only rows are sorted but columns are not? Commit yes or no.
Common Belief:If rows are sorted, the top-right corner search method will always work.
Tap to reveal reality
Reality:The method requires both rows and columns to be sorted. If columns are not sorted, the logic to move down or left breaks.
Why it matters:Using this method on partially sorted matrices can cause incorrect results or missed targets.
Quick: Is binary search on the entire matrix possible if only rows are sorted? Commit yes or no.
Common Belief:You can do a single binary search treating the matrix as a flat sorted list if rows are sorted.
Tap to reveal reality
Reality:This only works if the entire matrix is sorted as if flattened (rows and columns sorted in order). If only rows are sorted, you must do binary search on each row separately.
Why it matters:Trying a single binary search on partially sorted matrices leads to wrong answers and wasted effort.
Quick: Does starting search from bottom-left corner work the same as top-right? Commit yes or no.
Common Belief:Starting from bottom-left corner is not useful for efficient search.
Tap to reveal reality
Reality:Starting from bottom-left corner works similarly but in reverse: if target > current, move right; if target < current, move up.
Why it matters:Knowing both start points gives flexibility in implementation and understanding of the algorithm.
Expert Zone
1
The choice of starting point (top-right vs bottom-left) can affect code readability and slight performance differences depending on matrix shape.
2
In very large matrices, cache locality and memory access patterns can impact performance beyond algorithmic complexity.
3
Preprocessing the matrix into a segment tree or binary indexed tree can allow faster repeated queries but adds complexity.
When NOT to use
Do not use the efficient search if the matrix is unsorted or only partially sorted. Instead, use linear search or preprocess the data into hash maps or balanced trees for fast lookups.
Production Patterns
In real systems, this search is used in image processing to find pixel values, in databases for range queries on sorted data, and in geographic information systems to locate points in grids quickly.
Connections
Binary Search
Builds-on
Understanding binary search on a single sorted list helps grasp why searching each row with binary search works when only rows are sorted.
Divide and Conquer Algorithms
Shares pattern
The search eliminates large parts of the matrix at each step, similar to how divide and conquer algorithms reduce problem size quickly.
Geographic Grid Navigation
Analogous process
Navigating a sorted 2D matrix is like moving through a geographic grid where you decide direction based on conditions, helping understand spatial search strategies.
Common Pitfalls
#1Assuming the matrix is sorted only by rows and applying the top-right corner search.
Wrong approach:function searchMatrix(matrix, target) { 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; } // Used on matrix with only rows sorted, columns unsorted
Correct approach:function searchMatrix(matrix, target) { for (let row = 0; row < matrix.length; row++) { let low = 0, high = matrix[0].length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); if (matrix[row][mid] === target) return true; else if (matrix[row][mid] < target) low = mid + 1; else high = mid - 1; } } return false; } // Binary search on each row for partially sorted matrix
Root cause:Misunderstanding the sorting requirements of the efficient search algorithm.
#2Trying to flatten the matrix and do a single binary search when only rows are sorted.
Wrong approach:function searchMatrix(matrix, target) { let flat = matrix.flat(); let low = 0, high = flat.length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); if (flat[mid] === target) return true; else if (flat[mid] < target) low = mid + 1; else high = mid - 1; } return false; } // Incorrect if matrix is not fully sorted
Correct approach:Use binary search on each row separately as shown in previous correct approach.
Root cause:Confusing row-wise sorting with full matrix sorting.
#3Starting search from top-left corner and moving only right or down.
Wrong approach:function searchMatrix(matrix, target) { let row = 0; let col = 0; while (row < matrix.length && col < matrix[0].length) { if (matrix[row][col] === target) return true; else if (matrix[row][col] < target) col++; else row++; } return false; } // Incorrect logic
Correct approach:Start from top-right corner and move left or down as per comparison.
Root cause:Not understanding how sorted order allows elimination of rows or columns.
Key Takeaways
A 2D matrix is a grid of rows and columns where each element can be accessed by its row and column index.
Searching every element one by one works but is slow for large matrices.
If the matrix is sorted by rows and columns, starting from the top-right corner allows efficient search by eliminating rows or columns at each step.
Binary search on each row is useful when only rows are sorted, but not columns.
Understanding the sorting properties of the matrix is crucial to choosing the right search method.

Practice

(1/5)
1. What is the main idea behind searching a target value in a 2D matrix where each row and column is sorted in ascending order?
easy
A. Use binary search on each row independently
B. Start from bottom-left corner and move right or down based on comparison
C. Search each element one by one from top-left to bottom-right
D. Start from top-right corner and move left or down based on comparison

Solution

  1. Step 1: Understand matrix properties

    Each row and column is sorted ascending, so top-right element is a good start to decide direction.
  2. Step 2: Use top-right corner to guide search

    If target is less than current element, move left; if greater, move down.
  3. Final Answer:

    Start from top-right corner and move left or down based on comparison -> Option D
  4. Quick Check:

    Top-right start = efficient search [OK]
Hint: Start at top-right to decide move direction quickly [OK]
Common Mistakes:
  • Searching all elements one by one wastes time
  • Starting from bottom-left without clear logic
  • Using binary search on each row ignores column sorting
2. Which of the following is the correct syntax to check if a target exists in a 2D matrix named matrix in JavaScript?
easy
A. for(let i=0; i
B. for(let i=0; i
C. for(let i=0; i
D. for(let i=0; i

Solution

  1. Step 1: Identify correct loop ranges

    Outer loop runs over rows (matrix.length), inner loop over columns (matrix[0].length).
  2. Step 2: Check element equality with strict equality

    Use === for exact match and return true if found.
  3. Final Answer:

    for(let i=0; i -> Option B
  4. Quick Check:

    Correct loop ranges and strict equality [OK]
Hint: Outer loop rows, inner loop columns, use === for comparison [OK]
Common Mistakes:
  • Swapping row and column lengths in loops
  • Using == instead of === causing type coercion
  • Looping inner loop with wrong length causing errors
3. What will be the output of the following code snippet?
const matrix = [
  [1, 4, 7, 11],
  [2, 5, 8, 12],
  [3, 6, 9, 16],
  [10, 13, 14, 17]
];
const target = 5;

function searchMatrix(matrix, target) {
  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;
}

console.log(searchMatrix(matrix, target));
medium
A. Error
B. false
C. true
D. undefined

Solution

  1. Step 1: Start from top-right element

    Initial position is matrix[0][3] = 11, compare with target 5.
  2. Step 2: Move left since 11 > 5, now at matrix[0][2] = 7

    7 > 5, move left again to matrix[0][1] = 4.
  3. Step 3: 4 < 5, move down to matrix[1][1] = 5

    Found target 5, return true.
  4. Final Answer:

    true -> Option C
  5. Quick Check:

    Top-right search finds 5 = true [OK]
Hint: Move left if bigger, down if smaller from top-right [OK]
Common Mistakes:
  • Starting from wrong corner causing wrong moves
  • Not updating row or column correctly
  • Returning false too early without full search
4. Find the bug in the following code that searches for a target in a 2D matrix where rows and columns are sorted.
function searchMatrix(matrix, target) {
  let row = matrix.length - 1;
  let col = 0;
  while(row >= 0 && col < matrix[0].length) {
    if(matrix[row][col] === target) return true;
    else if(matrix[row][col] < target) row--;
    else col++;
  }
  return false;
}
medium
A. The directions to move row and col are swapped in conditions
B. The initial row and col values are incorrect
C. The while loop condition should use '||' instead of '&&'
D. The function should return false inside the loop

Solution

  1. Step 1: Analyze movement logic

    Starting at bottom-left, if current < target, should move right (col++), else move up (row--).
  2. Step 2: Check conditions in code

    Code moves row-- when current < target, which is wrong; it should move col++ instead.
  3. Final Answer:

    The directions to move row and col are swapped in conditions -> Option A
  4. Quick Check:

    Correct move directions fix search [OK]
Hint: From bottom-left, move right if smaller, up if bigger [OK]
Common Mistakes:
  • Swapping row and column moves
  • Wrong initial position for search
  • Incorrect loop condition causing infinite loop
5. Given a 2D matrix where each row and column is sorted ascending, write a function to count how many times a target appears in the matrix efficiently. Which approach is best?
hard
A. Start from top-right and move left/down counting matches (O(m+n))
B. Traverse entire matrix counting matches (O(m*n))
C. Use binary search on each row and sum counts (O(m*log n))
D. Flatten matrix to 1D array and use binary search once (O(m*n))

Solution

  1. Step 1: Understand time complexities

    Full traversal is slow (O(m*n)), binary search per row is better but still costly.
  2. Step 2: Use top-right start to count efficiently

    Moving left/down lets you skip rows or columns, counting matches in O(m+n) time.
  3. Final Answer:

    Start from top-right and move left/down counting matches (O(m+n)) -> Option A
  4. Quick Check:

    Top-right traversal counts efficiently [OK]
Hint: Top-right start counts matches in linear time [OK]
Common Mistakes:
  • Using full traversal wasting time
  • Flattening matrix losing sorted structure
  • Binary search per row misses column info
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard