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:
# 1D index → 2D coordinates
row = index // cols
col = index % cols
# 2D coordinates → 1D index
index = row * cols + colCommon 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
row = index // cols # Integer division
col = index % cols # Modulo (remainder)Why it works:
- Each row has
colselements index // colstells us which row (how many complete rows fit)index % colstells us position within that row
2D to 1D
Given: Row, column, number of columns
Find: 1D index
index = row * cols + colWhy it works:
row * colsskips all previous rows+ coladds position within current row
Visual Example
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:
row = mid % cols # WRONG
col = mid // cols # WRONG✅ Correct:
row = mid // cols # Correct
col = mid % cols # CorrectExample
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:
row = mid // rows # WRONG: should be cols
col = mid % rows # WRONG: should be cols✅ Correct:
row = mid // cols # Correct
col = mid % cols # CorrectExample
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:
rows, cols = len(matrix), len(matrix[0])
right = rows * cols # WRONG: should be -1✅ Correct:
rows, cols = len(matrix), len(matrix[0])
right = rows * cols - 1 # Correct: 0-indexedExample
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
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 FalseVerification Examples
Example 1: Small Matrix
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
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
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
colsin both formulas (notrows)? -
right = rows * cols - 1(not justrows * cols)? -
Getting
rowsandcolsfrom correct dimensions?
Quick Test
Test your formula on these:
# 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:
depth = index // (rows * cols)
row = (index % (rows * cols)) // cols
col = index % colsQ: Can I use this for column-major order?
A: Yes, but swap the formulas:
col = index // rows
row = index % rowsConclusion
Index mapping for 2D matrix binary search is straightforward once you know the formula.
The formula:
row = index // cols
col = index % colsCommon mistakes:
- Swapping
//and% - Using
rowsinstead ofcols - Off-by-one in
rightinitialization
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
