VOOZH about

URL: https://www.geeksforgeeks.org/dsa/divide-1-n-two-groups-minimum-sum-difference/

⇱ Divide 1 to n into two groups with minimum sum difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Divide 1 to n into two groups with minimum sum difference

Last Updated : 15 Mar, 2025

Given a positive integer n, such that n > 2. Your task is to divide the numbers from 1 to n in two groups, such that the absolute difference between the sum of the elements of the these two groups is minimum possible.

Examples:

Input: n = 5
Output: [ [ 2, 5 ], [ 1, 3, 4 ] ]
Explanation: The sum of first and second group are 7 and 8 respectively, and the difference is 8 - 7 = 1, which is the minimum possible. [ [ 1, 2, 5 ], [ 3, 4 ] ] is also the possible solution.

Input: n = 7
Output: [ [ 1, 6, 7 ], [ 2, 3, 4, 5 ] ]
Explanation: The sum of first and second group are 14 and 14 respectively, and the difference is 14 - 14 = 0, which is the minimum possible.

  • It can be observed that numbers 1 to n, can always be divided in to two groups, such that the difference of sum of elements is either 0 or 1.
  • The idea is to firstly compute the sum of elements from 1 to n (which is equal to n * (n + 1) / 2), then find the half of it.

[Naive Solution] - Dynamic Programming - O(n^3) Time

This problem can be reduced to the subset sum problem. We mainly need to find a subset of [1, 2, ... n] whose sum is closest to half of n*(n+1)/2. The time complexity of this solution would be O(n^3).


Output
Subset 1: 1 4 
Subset 2: 2 3 

[Expected Solution[ - Greedy Approach - O(n) Time

We traverse numbers from n to 1. And we try adding every number to the first subset. If adding the number does not make the sum more than half, we add the number to first subset, else to the second.

We create two auxiliary arrays to store the elements of two groups, and initiate two counters to store the sum of elements of both the groups. Now start iterating from 1 to n, and insert the element in the first group if it does not exceed the first group's sum more than the calculated half sum, else insert the element in second group.


Output
7 6 1 
5 4 3 2 

Time Complexity: O(n), as we are iterating from n to 1 only once.
Space Complexity: O(n), to store the elements from 1 to n in two groups.

Comment