LeetCode Entry
1337. The K Weakest Rows in a Matrix
k indices with smallest row sum in a binary matrix
1337. The K Weakest Rows in a Matrix easy
blog post
substack

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
- map
- filter
- sortedBy https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted-by.html
- take
- toIntArray
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()