# 2.01.2024 [2610. Convert an Array Into a 2D Array With Conditions]
Convert numbers array into array of unique number-rows.
2.01.2024
2610. Convert an Array Into a 2D Array With Conditions medium
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/459
Problem TLDR
Convert numbers array into array of unique number-rows.
Intuition
Let’s count each kind of number, then use each unique number to build the rows.
Approach
Kotlin’s API can be helpful:
groupBy
mapValues
buildList
Complexity
Time complexity:
O(uf) where, u - number of uniq elements, f - max frequency. Worst case O(n^2):1 2 3 4 1 1 1 1
, u = n / 2, f = n / 2. This can be improved to O(n) by removing the empty collections fromfreq
.Space complexity:
O(n)
Code
fun findMatrix(nums: IntArray): List<List<Int>> {
val freq = nums.groupBy { it }
.mapValues { it.value.toMutableList() }
return buildList {
repeat(freq.values.maxOf { it.size }) {
add(buildList {
for ((k, v) in freq)
if (v.isNotEmpty()) add(v.removeLast())
})
}
}
}