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
Find Smallest Common Element in All RowsInput Matrix (sorted rows):12345245810357911Analysis:• Element 1: only in row 0• Element 2: only in rows 0,1• Element 3: only in rows 0,2✓ Element 5: in ALL rows!Output: 5Element 5 is the smallest common element in all rows
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
Asked in
Google 25 Amazon 18 Microsoft 12
52.4K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen