Find Smallest Common Element in All Rows - Problem
Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows.
If there is no common element, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11]]
›
Output:
5
💡 Note:
Element 5 appears in all three rows: row 0 at index 4, row 1 at index 2, and row 2 at index 1. It's the smallest such common element.
Example 2 — No Common Element
$
Input:
mat = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
-1
💡 Note:
No element appears in all three rows. Each row has completely different elements, so return -1.
Example 3 — Multiple Common Elements
$
Input:
mat = [[1,2,3,4,5],[1,3,5,7,9],[1,4,5,8,9]]
›
Output:
1
💡 Note:
Elements 1 and 5 appear in all rows, but 1 is smaller than 5, so return 1.
Constraints
- 1 ≤ m, n ≤ 500
- 1 ≤ mat[i][j] ≤ 104
- mat[i] is sorted in strictly increasing order
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Each row is sorted in increasing order
2
Search Process
Check which elements appear in all rows
3
Result
Return the smallest common element or -1
Key Takeaway
🎯 Key Insight: Use the sorted property of rows with binary search to efficiently find common elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code