445. Find Smallest Common Element in All Rows

EasyBinary SearchArrayMatrixBinary SearchHashing

Given an m×n matrix where each row is sorted in increasing order, find and return the smallest common element among all rows. Return -1 if no common element exists.

Input: A 2D integer matrix where each row is sorted in ascending order.

Output: The smallest common element across all rows, or -1.

Examples

Example 1
Input: [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output: 5
Explanation: 5 appears in all 4 rows. It is the only common element.
Example 2
Input: [[1,2,3],[1,4,5],[1,6,7]]
Output: 1
Explanation: 1 appears in all rows; it is the smallest (and only) common.
Example 3
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: -1
Explanation: No element common to all rows.

Constraints

Asked by

Microsoft
Solve this problem in the editor →