LeetCode Entry
2966. Divide Array Into Arrays With Max Difference
Split array into tripples with at most k difference.
2966. Divide Array Into Arrays With Max Difference medium
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/491
Problem TLDR
Split array into tripples with at most k difference.
Intuition
Sort, then just check k condition.
Approach
Let’s use iterators in Kotlin and Rust:
- chunked vs chunks
- sorted() vs sort_unstable() (no sorted iterator in Rust)
- takeIf() vs ..
- all() vs any()
- .. map(), to_vec(), collect(), vec![]
Complexity
-
Time complexity: \(O(nlog(n))\)
-
Space complexity: \(O(n)\)
Code
fun divideArray(nums: IntArray, k: Int) = nums
.sorted().chunked(3).toTypedArray()
.takeIf { it.all { it[2] - it[0] <= k } } ?: arrayOf()
pub fn divide_array(mut nums: Vec<i32>, k: i32) -> Vec<Vec<i32>> {
nums.sort_unstable();
if nums.chunks(3).any(|c| c[2] - c[0] > k) { vec![] }
else { nums.chunks(3).map(|c| c.to_vec()).collect() }
}