Find Smallest Common Element in All Rows - Problem

You're given an m x n matrix where each row is sorted in strictly increasing order. Your task is to find the smallest element that appears in every single row of the matrix.

Think of it like finding a common favorite among different groups - you need an element that shows up in all rows, and if there are multiple such elements, you want the smallest one.

Example: If you have a matrix like [[1,2,3,4],[2,3,4,5],[3,4,5,6]], the elements that appear in all rows are [3,4], so you should return 3 since it's the smallest.

If no element appears in all rows, return -1.

The key insight here is leveraging the fact that each row is already sorted - this gives us multiple optimization opportunities!

Input & Output

example_1.py โ€” Basic Case
$ Input: mat = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
โ€บ Output: 3
๐Ÿ’ก Note: Elements that appear in all rows: [3,4]. The smallest is 3.
example_2.py โ€” No Common Elements
$ Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
โ€บ Output: -1
๐Ÿ’ก Note: No element appears in all three rows, so return -1.
example_3.py โ€” Single Common Element
$ Input: mat = [[1,2,3,4,5],[2,3,4],[2,3,4,4,5,6]]
โ€บ Output: 2
๐Ÿ’ก Note: Elements 2, 3, and 4 appear in all rows. The smallest is 2.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 โ‰ค m, n โ‰ค 1000
  • 1 โ‰ค mat[i][j] โ‰ค 104
  • Each row is sorted in strictly increasing order

Visualization

Tap to expand
Matrix: Finding Smallest Common ElementRow 1: [1,2,3,4]Row 2: [2,3,4,5]Row 3: [3,4,5,6]123423453456Element 3 found in all rows!Element 4 also found in all rows!Answer: 3 (smallest common)Binary Search Approach:1. Check element 1 from row 1 โ†’ Not in row 2 โœ—2. Check element 2 from row 1 โ†’ Not in row 3 โœ—3. Check element 3 from row 1 โ†’ Found in all rows โœ“Time: O(m ร— n ร— log n) vs O(m ร— nยฒ) brute force
Understanding the Visualization
1
Start with first catalog
Since it's sorted by price, checking in order guarantees we find the cheapest first
2
Search other catalogs efficiently
Use the sorted nature - binary search instead of scanning every book
3
Return first match
The first book found in all catalogs is guaranteed to be the cheapest
Key Takeaway
๐ŸŽฏ Key Insight: Use the sorted property of each row! Binary search reduces lookup time from O(n) to O(log n), making the overall solution much more efficient.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
42.8K Views
Medium Frequency
~15 min Avg. Time
1.2K 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