LeetCode Entry
2610. Convert an Array Into a 2D Array With Conditions
Convert numbers array into array of unique number-rows.
2610. Convert an Array Into a 2D Array With Conditions medium blog post substack youtube \) 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())
})
}
}
}