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 Rows INPUT Matrix mat (3x5, sorted rows) Row 0: 1 2 3 4 5 Row 1: 2 4 5 8 10 Row 2: 3 5 7 9 11 Element Count Map Elem Count 1 1 2 2 3 2 4 2 5 3 (=m) 7,8,9... 1 ALGORITHM STEPS 1 Count Elements Use HashMap to count occurrences of each element 2 Iterate Row by Row For each row, increment count for each element 3 Check Count = m If count equals num rows, element exists in all rows 4 Return Smallest Return first element with count=m (sorted order) Counting Process map[5]++ at row 0 map[5]++ at row 1 map[5]++ at row 2 map[5] = 3 = m --> OK! FINAL RESULT Smallest Common Element Found 5 Output: 5 Verification Row 0: [1,2,3,4,5] has 5 OK Row 1: [2,4,5,8,10] has 5 OK Row 2: [3,5,7,9,11] has 5 OK 5 appears in all 3 rows! Complexity Time: O(m*n) | Space: O(m*n) Key Insight: Since each row is sorted in strictly increasing order (no duplicates within a row), we can count element occurrences across all rows. An element that appears exactly m times (where m = number of rows) must be present in every row. Processing in order ensures we find the smallest such element first. TutorialsPoint - Find Smallest Common Element in All Rows | Optimal Solution (HashMap Counting)
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