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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 return (*(int*)a - *(int*)b);
6}
7
8void divideArrayIntoGroups(int* nums, int numsSize, int k, int(*result)[3], int* returnSize) {
9 qsort(nums, numsSize, sizeof(int), compare);
10 int index = 0;
11 *returnSize = numsSize / 3;
12
13 for (int i = 0; i < numsSize; i += 3) {
14 if (i + 2 < numsSize && nums[i+2] - nums[i] <= k) {
15 result[index][0] = nums[i];
16 result[index][1] = nums[i+1];
17 result[index][2] = nums[i+2];
18 index++;
19 } else {
20 *returnSize = 0;
21 return;
22 }
23 }
24}
25
26int main() {
27 int nums[] = {1,3,4,8,7,9,3,5,1};
28 int k = 2;
29 int numsSize = sizeof(nums) / sizeof(nums[0]);
30 int returnSize;
31 int result[numsSize / 3][3];
32
33 divideArrayIntoGroups(nums, numsSize, k, result, &returnSize);
34
35 if (returnSize == 0) {
36 printf("[]\n");
37 } else {
38 for (int i = 0; i < returnSize; i++) {
39 printf("[%d, %d, %d]\n", result[i][0], result[i][1], result[i][2]);
40 }
41 }
42
43 return 0;
44}
This C solution first sorts the array using qsort
. It then iterates through the sorted array, forming groups of three numbers and ensuring that the difference between the smallest and largest number in each group is ≤ k
. If a valid group cannot be formed, it returns 0 indicating failure.
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.
This Python algorithm uses a sorted list and two pointers. It increments &&&i&&& and &&&j&&& to create valid groups of three numbers, ensuring they conform to the ≤ k
rule. If they cannot comply, an empty list signals failure.