LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Binary Search/2D Matrix Index Mapping in Binary Search: The Formula and Common Mistakes

2D Matrix Index Mapping in Binary Search: The Formula and Common Mistakes

LeetCopilot Team
Dec 30, 2025
6 min read
Binary Search2D MatrixIndex MappingCommon MistakesFormula
Master the 1D-to-2D index conversion formula for binary search on matrices. Learn row and column calculation, common off-by-one errors, and how to verify correctness.

Converting 1D binary search indices to 2D matrix coordinates is where most bugs happen in matrix binary search. The formula is simple, but getting row and column backwards or off-by-one in dimensions breaks everything.

This guide provides the exact formula, common mistakes, and how to verify your index mapping is correct.

TL;DR

The formula:

python
# 1D index → 2D coordinates
row = index // cols
col = index % cols

# 2D coordinates → 1D index
index = row * cols + col

Common mistakes:

  • Swapping row and col formulas
  • Using rows instead of cols in formula
  • Off-by-one in matrix dimensions

The Index Mapping Formula

1D to 2D

Given: 1D index, number of columns
Find: Row and column

python
row = index // cols  # Integer division
col = index % cols   # Modulo (remainder)

Why it works:

  • Each row has cols elements
  • index // cols tells us which row (how many complete rows fit)
  • index % cols tells us position within that row

2D to 1D

Given: Row, column, number of columns
Find: 1D index

python
index = row * cols + col

Why it works:

  • row * cols skips all previous rows
  • + col adds position within current row

Visual Example

code
Matrix (3 rows × 4 cols):
[0,  1,  2,  3]   ← row 0
[4,  5,  6,  7]   ← row 1
[8,  9, 10, 11]   ← row 2

1D representation: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Index 5 → 2D:
  row = 5 // 4 = 1
  col = 5 % 4 = 1
  → matrix[1][1] = 5 ✓

2D (row=2, col=3) → 1D:
  index = 2 * 4 + 3 = 11
  → array[11] = 11 ✓

Common Mistake 1: Wrong Row Calculation

The Problem

Using % instead of // for row.

Wrong:

python
row = mid % cols  # WRONG
col = mid // cols  # WRONG

Correct:

python
row = mid // cols  # Correct
col = mid % cols   # Correct

Example

code
Matrix (3×4), index = 5

Wrong:
  row = 5 % 4 = 1 ✓ (accidentally correct)
  col = 5 // 4 = 1 ✓ (accidentally correct)
  
But for index = 7:
  row = 7 % 4 = 3 ✗ (out of bounds! only 3 rows)
  col = 7 // 4 = 1 ✗

Correct:
  row = 7 // 4 = 1 ✓
  col = 7 % 4 = 3 ✓

Common Mistake 2: Wrong Column Calculation

The Problem

Using rows instead of cols in the formula.

Wrong:

python
row = mid // rows  # WRONG: should be cols
col = mid % rows   # WRONG: should be cols

Correct:

python
row = mid // cols  # Correct
col = mid % cols   # Correct

Example

code
Matrix (3 rows × 4 cols), index = 5

Wrong (using rows):
  row = 5 // 3 = 1
  col = 5 % 3 = 2
  → matrix[1][2] = 6 ✗ (should be 5)

Correct (using cols):
  row = 5 // 4 = 1
  col = 5 % 4 = 1
  → matrix[1][1] = 5 ✓

Common Mistake 3: Off-by-One in Dimensions

The Problem

Using wrong dimensions or forgetting 0-indexing.

Wrong:

python
rows, cols = len(matrix), len(matrix[0])
right = rows * cols  # WRONG: should be -1

Correct:

python
rows, cols = len(matrix), len(matrix[0])
right = rows * cols - 1  # Correct: 0-indexed

Example

code
Matrix (3×4) has 12 elements

Indices: 0, 1, 2, ..., 11

Wrong:
  right = 3 * 4 = 12 (out of bounds!)

Correct:
  right = 3 * 4 - 1 = 11 ✓

Complete Binary Search Template

python
def searchMatrix(matrix: List[List[int]], target: int) -> bool:
    """
    Binary search on fully sorted matrix
    
    Time: O(log(m × n))
    Space: O(1)
    """
    if not matrix or not matrix[0]:
        return False
    
    rows, cols = len(matrix), len(matrix[0])
    left, right = 0, rows * cols - 1
    
    while left <= right:
        mid = left + (right - left) // 2
        
        # Convert 1D index to 2D coordinates
        row = mid // cols  # Which row
        col = mid % cols   # Which column
        mid_value = matrix[row][col]
        
        if mid_value == target:
            return True
        elif mid_value < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return False

Verification Examples

Example 1: Small Matrix

code
Matrix (2×3):
[1, 3, 5]
[7, 9, 11]

Verify all indices:
  index 0: row=0//3=0, col=0%3=0 → [0][0]=1 ✓
  index 1: row=1//3=0, col=1%3=1 → [0][1]=3 ✓
  index 2: row=2//3=0, col=2%3=2 → [0][2]=5 ✓
  index 3: row=3//3=1, col=3%3=0 → [1][0]=7 ✓
  index 4: row=4//3=1, col=4%3=1 → [1][1]=9 ✓
  index 5: row=5//3=1, col=5%3=2 → [1][2]=11 ✓

Example 2: Single Row

code
Matrix (1×5):
[1, 2, 3, 4, 5]

Verify:
  index 0: row=0//5=0, col=0%5=0 → [0][0]=1 ✓
  index 4: row=4//5=0, col=4%5=4 → [0][4]=5 ✓

Example 3: Single Column

code
Matrix (5×1):
[1]
[2]
[3]
[4]
[5]

Verify:
  index 0: row=0//1=0, col=0%1=0 → [0][0]=1 ✓
  index 4: row=4//1=4, col=4%1=0 → [4][0]=5 ✓

Debugging Checklist

When your index mapping is wrong:

  • Using // for row, % for col?
  • Using cols in both formulas (not rows)?
  • right = rows * cols - 1 (not just rows * cols)?
  • Getting rows and cols from correct dimensions?

Quick Test

Test your formula on these:

python
# Matrix (3×4)
rows, cols = 3, 4

# Test cases
assert 0 // cols == 0 and 0 % cols == 0  # [0][0]
assert 3 // cols == 0 and 3 % cols == 3  # [0][3]
assert 4 // cols == 1 and 4 % cols == 0  # [1][0]
assert 11 // cols == 2 and 11 % cols == 3  # [2][3]

FAQ

Q: Why use cols, not rows?

A: Because we're dividing the 1D index by the number of elements per row (which is cols).

Q: Does this work for non-square matrices?

A: Yes! Works for any m×n matrix.

Q: What if I have a 3D matrix?

A: Similar principle:

python
depth = index // (rows * cols)
row = (index % (rows * cols)) // cols
col = index % cols

Q: Can I use this for column-major order?

A: Yes, but swap the formulas:

python
col = index // rows
row = index % rows

Conclusion

Index mapping for 2D matrix binary search is straightforward once you know the formula.

The formula:

python
row = index // cols
col = index % cols

Common mistakes:

  • Swapping // and %
  • Using rows instead of cols
  • Off-by-one in right initialization

Verification:

  • Test on small matrices
  • Check boundary indices (0 and last)
  • Verify dimensions are correct

Memory aid:

  • Row = how many complete rows (division)
  • Col = position within row (remainder)

Master this formula and you'll handle 2D matrix binary search with confidence. For more details, see 2D Matrix Binary Search and the Complete Binary Search Guide.

Want to Practice LeetCode Smarter?

LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.

Also compatible with Edge, Brave, and Opera

Related Tutorials