LeetCode Entry
1282. Group the People Given the Group Size They Belong To
Groups from groups sizes array
1282. Group the People Given the Group Size They Belong To medium
blog post
substack

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/336
Problem TLDR
Groups from groups sizes array
Intuition
First, group by sizes, next, chunk by groups size each.
Approach
Let’s write it using Kotlin collections API
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
// 2 1 3 3 3 2 1 1 1 2 2
// 0 1 2 3 4 5 6 7 8 9 10
// 2 -> 0 5 [9 10]
// 1 -> 1 [6] [7] [8]
// 3 -> 2 3 4
fun groupThePeople(groupSizes: IntArray) =
groupSizes
.withIndex()
.groupBy { it.value }
.flatMap { (sz, nums) ->
nums.map { it.index }.chunked(sz)
}