Sponsored
Sponsored
Sort the array to ensure that the smallest numbers are adjacent, making it easier to form groups where the maximum difference is less than or equal to k
. After sorting, iterate through the array and try to form groups of three. At each step, check if the difference between the first and third numbers in the potential group is less than or equal to k
. If yes, form the group; otherwise, return an empty array as it's impossible to meet the requirement.
Time Complexity: O(n log n), due to the sorting step.
Space Complexity: O(1), as no additional space is used beyond the input and output storage.
1function divideArrayIntoGroups(nums, k) {
2 nums.sort((a, b) => a - b);
3 const result = [];
4
5 for (let i = 0; i < nums.length; i+=3) {
6 if (i + 2 < nums.length && nums[i+2] - nums[i] <= k) {
7 result.push([nums[i], nums[i+1], nums[i+2]]);
8 } else {
9 return [];
10 }
11 }
12
13 return result;
14}
15
16// Example usage
17const nums = [1,3,4,8,7,9,3,5,1];
18const k = 2;
19console.log(divideArrayIntoGroups(nums, k));
This JavaScript solution sorts the array using the sort()
function with a custom comparator. It aims to create valid triplets by checking whether the difference between the smallest and largest numbers in each trio is ≤ k
. If not, an empty array is returned.
This approach uses a greedy technique with two pointers to form groups of three elements. Sort the array first. Maintain two pointers, &&&i&&& and &&&j&&&, where &&&i&&& points to the start of a possible group and &&&j&&& iterates over the array to form a group when the criteria are met. When the triplet satisfies the requirement, move to the next possible group.
Time Complexity: O(n log n) for sorting, O(n) for the two pointers traversal, making it O(n log n).
Space Complexity: O(n) due to allocated space for the resulting groups.
#include <vector>
#include <algorithm>
std::vector<std::vector<int>> divideArrayIntoGroups(std::vector<int>& nums, int k) {
std::sort(nums.begin(), nums.end());
std::vector<std::vector<int>> result;
size_t i = 0, j = 0;
while (j < nums.size()) {
if (j - i + 1 == 3) {
if (nums[j] - nums[i] <= k) {
result.push_back({nums[i], nums[i+1], nums[j]});
i = j + 1;
j = i;
} else {
return {};
}
} else {
++j;
}
}
return result;
}
int main() {
std::vector<int> nums = {1,3,4,8,7,9,3,5,1};
int k = 2;
auto result = divideArrayIntoGroups(nums, k);
if (result.empty()) {
std::cout << "[]" << std::endl;
} else {
for (const auto& group : result) {
std::cout << "[" << group[0] << ", " << group[1] << ", " << group[2] << "]" << std::endl;
}
}
return 0;
}
This C++ uses a greedy two-pointer strategy. After sorting, it attempts to form groups using the pointers, &&&i&&& and &&&j&&&, ensuring groups of three have an appropriate difference. If viable, it generates the group; if not, it returns an empty vector, indicating failure.