LeetCode Entry

1337. The K Weakest Rows in a Matrix

18.09.2023 easy 2023 kotlin

k indices with smallest row sum in a binary matrix

1337. The K Weakest Rows in a Matrix easy blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/343

Problem TLDR

k indices with smallest row sum in a binary matrix

Intuition

We can precompute row sums, then use a Priority Queue to find k smallest. However, just sorting all will also work.

Approach

Let’s use Kotlin’s collections API

Complexity

  • Time complexity: \(O(n^2logn)\)

  • Space complexity: \(O(n^2)\)

Code


    fun kWeakestRows(mat: Array<IntArray>, k: Int) = mat
        .map { it.filter { it == 1 }.sum() ?: 0 }
        .withIndex()
        .sortedBy { it.value }
        .map { it.index }
        .take(k)
        .toIntArray()