Find Smallest Common Element in All Rows

medium matrix hash map counting

Problem

Given an m × 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.

Inputmat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output5
5 is the smallest value that appears in all four rows.

def smallest_common_element(mat):
    rows = len(mat)
    count = {}
    for row in mat:
        for x in row:
            count[x] = count.get(x, 0) + 1
            if count[x] == rows:
                return x
    return -1
function smallestCommonElement(mat) {
  const rows = mat.length;
  const count = new Map();
  for (const row of mat) {
    for (const x of row) {
      const c = (count.get(x) || 0) + 1;
      count.set(x, c);
      if (c === rows) return x;
    }
  }
  return -1;
}
class Solution {
    public int smallestCommonElement(int[][] mat) {
        int rows = mat.length;
        Map<Integer, Integer> count = new HashMap<>();
        for (int[] row : mat) {
            for (int x : row) {
                int c = count.getOrDefault(x, 0) + 1;
                count.put(x, c);
                if (c == rows) return x;
            }
        }
        return -1;
    }
}
int smallestCommonElement(vector<vector<int>>& mat) {
    int rows = mat.size();
    unordered_map<int, int> count;
    for (auto& row : mat) {
        for (int x : row) {
            if (++count[x] == rows) return x;
        }
    }
    return -1;
}
Time: O(m·n) Space: O(n)