LeetCode Entry

1380. Lucky Numbers in a Matrix

19.07.2024 easy 2024 kotlin rust

Min in rows and max in columns in a unique number matrix

1380. Lucky Numbers in a Matrix easy blog post substack youtube 2024-07-19_08-22_1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/675

Problem TLDR

Min in rows and max in columns in a unique number matrix #easy

Intuition

As all the numbers are unique, we can first find all the maximums in the columns, then intersect the result with all the minimums in the rows.

Approach

Let’s use the collections API’s:

  • maxOf, map, filter

Complexity

  • Time complexity: \(O(nm)\)

  • Space complexity: \(O(nm)\)

Code


    fun luckyNumbers (matrix: Array<IntArray>) = (0..<matrix[0].size)
        .map { x -> matrix.maxOf { it[x] }}.toSet().let { maxes ->
            matrix.map { it.min() }.filter { it in maxes }}


    pub fn lucky_numbers (matrix: Vec<Vec<i32>>) -> Vec<i32> {
        let maxes: Vec<_> = (0..matrix[0].len())
            .map(|x| matrix.iter().map(|r| r[x]).max().unwrap()).collect();
        matrix.iter().map(|r| *r.iter().min().unwrap())
            .filter(|v| maxes.contains(v)).collect()
    }