How to find a common element in all rows of a given matrix with sorted rows in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn find_common_element_in_matrix_rows(matrix: &[Vec<i32>]) -> i32 {
    let rows = matrix.len();
    if rows == 0 {
        return -1;
    }

    let cols = matrix[0].len();
    let mut freq: HashMap<i32, usize> = HashMap::new();

    for row in matrix {
        freq.entry(row[0]).and_modify(|c| *c += 1).or_insert(1);
        for j in 1..cols {
            if row[j] != row[j - 1] {
                freq.entry(row[j]).and_modify(|c| *c += 1).or_insert(1);
            }
        }
    }

    for (key, count) in freq {
        if count == rows {
            return key;
        }
    }

    -1
}

fn main() {
    let matrix = vec![
        vec![1, 2, 3, 5, 36],
        vec![4, 5, 7, 9, 10],
        vec![5, 6, 8, 9, 18],
        vec![1, 3, 5, 8, 24],
    ];

    let result = find_common_element_in_matrix_rows(&matrix);
    if result != -1 {
        println!("Common element in all rows: {}", result);
    } else {
        println!("No common element found in all rows.");
    }
}



/*
run:

Common element in all rows: 5

*/

 



answered Oct 3, 2025 by avibootz
...