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.
1import java.util.*;
2
3public class DivideArray {
4 public static List<int[]> divideArrayIntoGroups(int[] nums, int k) {
5 Arrays.sort(nums);
6 List<int[]> result = new ArrayList<>();
7
8 for (int i = 0; i < nums.length; i += 3) {
9 if (i + 2 < nums.length && nums[i+2] - nums[i] <= k) {
10 result.add(new int[]{nums[i], nums[i+1], nums[i+2]});
11 } else {
12 return Collections.emptyList();
13 }
14 }
15
16 return result;
17 }
18
19 public static void main(String[] args) {
20 int[] nums = {1,3,4,8,7,9,3,5,1};
21 int k = 2;
22 List<int[]> result = divideArrayIntoGroups(nums, k);
23
24 if (result.isEmpty()) {
25 System.out.println("[]");
26 } else {
27 for (int[] group : result) {
28 System.out.println(Arrays.toString(group));
29 }
30 }
31 }
32}
The Java solution sorts the array using Arrays.sort()
. It iterates over the array in increments of three, checking if the difference between the first and last of the three is within the limits specified by k
. If grouping fails at any point, the function returns an empty List.
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 C implementation uses a sorted array and a two-pointer technique. Pointers &&&i&&& and &&&j&&& are used to track possible triplets. The solution evaluates whether formed groups satisfy the maximum difference ≤ k
. If a triplet exceeds the maximum difference, it raises an error and exits as formation is impractical.