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.
1using System;
2using System.Collections.Generic;
3
4class Program {
5 public static List<int[]> DivideArrayIntoGroups(int[] nums, int k) {
6 Array.Sort(nums);
7 var result = new List<int[]>();
8
9 for (int i = 0; i < nums.Length; i += 3) {
10 if (i + 2 < nums.Length && nums[i + 2] - nums[i] <= k) {
11 result.Add(new int[] { nums[i], nums[i+1], nums[i+2] });
12 } else {
13 return new List<int[]>();
14 }
15 }
16
17 return result;
18 }
19
20 static void Main() {
21 int[] nums = { 1, 3, 4, 8, 7, 9, 3, 5, 1 };
22 int k = 2;
23 var result = DivideArrayIntoGroups(nums, k);
24
25 if (result.Count == 0) {
26 Console.WriteLine("[]");
27 } else {
28 foreach (var group in result) {
29 Console.WriteLine(string.Join(", ", group));
30 }
31 }
32 }
33}
This C# solution sorts the array using Array.Sort()
. It loops through the sorted array in steps of 3 and checks if the difference between maximum and minimum of each trio is within the allowed limit k
. If a valid group is not possible, an empty list 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.
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.