Given an integer N, split the first N natural numbers into two sets such that the absolute difference between their sum is minimum. The task is to print the minimum absolute difference that can be obtained.
Examples:
Input: N = 5
Output: 1
Explanation:
Split the first N (= 5) natural numbers into sets {1, 2, 5} (sum = 8) and {3, 4} (sum = 7).
Therefore, the required output is 1.
Input: N = 6
Output: 1
Naive Approach: This problem can be solved using the Greedy technique. Follow the steps below to solve the problem:
- Initialize two variables, say sumSet1 and sumSet2 to store the sum of the elements from the two sets.
- Traverse first N natural numbers from N to 1. For every number, check if the current sum of elements in set1 is less than or equal to the sum of elements in set2. If found to be true, add the currently traversed number into set1 and update sumSet1.
- Otherwise, add the value of the current natural number to set2 and update sumSet2.
- Finally, print abs(sumSet1 – sumSet2) as the required answer.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int minAbsDiff( int N)
{
int sumSet1 = 0;
int sumSet2 = 0;
for ( int i = N; i > 0; i--) {
if (sumSet1 <= sumSet2) {
sumSet1 += i;
}
else {
sumSet2 += i;
}
}
return abs (sumSet1 - sumSet2);
}
int main()
{
int N = 6;
cout << minAbsDiff(N);
}
|
Java
import java.io.*;
class GFG{
static int minAbsDiff( int N)
{
int sumSet1 = 0 ;
int sumSet2 = 0 ;
for ( int i = N; i > 0 ; i--)
{
if (sumSet1 <= sumSet2)
{
sumSet1 += i;
}
else
{
sumSet2 += i;
}
}
return Math.abs(sumSet1 - sumSet2);
}
public static void main (String[] args)
{
int N = 6 ;
System.out.println(minAbsDiff(N));
}
}
|
Python3
def minAbsDiff(N):
sumSet1 = 0
sumSet2 = 0
for i in reversed ( range (N + 1 )):
if sumSet1 < = sumSet2:
sumSet1 = sumSet1 + i
else :
sumSet2 = sumSet2 + i
return abs (sumSet1 - sumSet2)
N = 6
print (minAbsDiff(N))
|
C#
using System;
class GFG{
static int minAbsDiff( int N)
{
int sumSet1 = 0;
int sumSet2 = 0;
for ( int i = N; i > 0; i--)
{
if (sumSet1 <= sumSet2)
{
sumSet1 += i;
}
else
{
sumSet2 += i;
}
}
return Math.Abs(sumSet1 - sumSet2);
}
static void Main()
{
int N = 6;
Console.Write(minAbsDiff(N));
}
}
|
Javascript
<script>
function minAbsDiff(N)
{
var sumSet1 = 0;
var sumSet2 = 0;
for (i = N; i > 0; i--)
{
if (sumSet1 <= sumSet2)
{
sumSet1 += i;
}
else
{
sumSet2 += i;
}
}
return Math.abs(sumSet1 - sumSet2);
}
var N = 6;
document.write(minAbsDiff(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is based on the following observations:
Splitting any 4 consecutive integers into 2 sets gives the minimum absolute difference of their sum equal to 0.
Mathematical proof:
Considering 4 consecutive integers {a1, a2, a3, a4}
a4 = a3 + 1
a1=a2 – 1
=> a4 + a1 = a3 + 1 + a2 – 1
=> a4 + a1 = a2 + a3
Follow the steps below to solve the problem:
- If N % 4 == 0 or N % 4 == 3, then print 0.
- Otherwise, print 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minAbsDiff( int N)
{
if (N % 4 == 0 || N % 4 == 3) {
return 0;
}
return 1;
}
int main()
{
int N = 6;
cout << minAbsDiff(N);
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static int minAbsDiff( int N)
{
if (N % 4 == 0 || N % 4 == 3 )
{
return 0 ;
}
return 1 ;
}
public static void main (String[] args)
{
int N = 6 ;
System.out.println(minAbsDiff(N));
}
}
|
Python3
def minAbsDiff(N):
if (N % 4 = = 0 or N % 4 = = 3 ):
return 0
return 1
N = 6
print (minAbsDiff(N))
|
C#
using System;
class GFG{
static int minAbsDiff( int N)
{
if (N % 4 == 0 ||
N % 4 == 3)
{
return 0;
}
return 1;
}
public static void Main(String[] args)
{
int N = 6;
Console.WriteLine(minAbsDiff(N));
}
}
|
Javascript
<script>
function minAbsDiff(N) {
if (N % 4 == 0 || N % 4 == 3) {
return 0;
}
return 1;
}
var N = 6;
document.write(minAbsDiff(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach 3:
Approach:
- Create a set of the first N natural numbers.
- Initialize a variable min_diff to infinity to keep track of the minimum absolute difference found so far.
- Loop through all possible subsets of the set of numbers. Since we are only interested in splitting the set into two subsets, we can loop through all
- binary numbers from 1 to 2^(N-1), where each bit in the binary number represents whether the corresponding number in the set belongs to subset1 or subset2.
- For each subset, calculate the absolute difference between the sum of the numbers in subset1 and subset2.
- If the absolute difference is less than the current minimum difference, update the minimum difference.
- After all subsets have been checked, return the minimum absolute difference found.
C++
#include <climits>
#include <cmath>
#include <iostream>
#include <numeric>
#include <set>
int minAbsoluteDiff( int N)
{
std::set< int > numSet;
for ( int i = 1; i <= N; i++) {
numSet.insert(i);
}
int minDiff = INT_MAX;
for ( int i = 1; i < std:: pow (2, N - 1); i++) {
std::set< int > subset1, subset2;
for ( int j = 0; j < N; j++) {
if (i & (1 << j)) {
subset1.insert(j + 1);
}
else {
subset2.insert(j + 1);
}
}
int sum1 = std::accumulate(subset1.begin(),
subset1.end(), 0);
int sum2 = std::accumulate(subset2.begin(),
subset2.end(), 0);
int diff = std:: abs (sum1 - sum2);
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
int main()
{
std::cout << minAbsoluteDiff(5)
<< std::endl;
std::cout << minAbsoluteDiff(6)
<< std::endl;
return 0;
}
|
Java
import java.util.HashSet;
import java.util.Set;
public class MinAbsoluteDiff {
public static int minAbsoluteDiff( int N) {
Set<Integer> numSet = new HashSet<>();
for ( int i = 1 ; i <= N; i++) {
numSet.add(i);
}
int minDiff = Integer.MAX_VALUE;
for ( int i = 1 ; i < ( 1 << (N - 1 )); i++) {
Set<Integer> subset1 = new HashSet<>();
Set<Integer> subset2 = new HashSet<>();
for ( int j = 0 ; j < N; j++) {
if ((i & ( 1 << j)) != 0 ) {
subset1.add(j + 1 );
} else {
subset2.add(j + 1 );
}
}
int diff = Math.abs(sum(subset1) - sum(subset2));
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
public static int sum(Set<Integer> set) {
int sum = 0 ;
for ( int num : set) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
System.out.println(minAbsoluteDiff( 5 ));
System.out.println(minAbsoluteDiff( 6 ));
}
}
|
Python3
def min_absolute_diff(N):
num_set = set ( range ( 1 ,N + 1 ))
min_diff = float ( 'inf' )
for i in range ( 1 , 2 * * (N - 1 )):
subset1 = set ()
subset2 = set ()
for j in range (N):
if i & ( 1 <<j):
subset1.add(j + 1 )
else :
subset2.add(j + 1 )
diff = abs ( sum (subset1) - sum (subset2))
if diff < min_diff:
min_diff = diff
return min_diff
print (min_absolute_diff( 5 ))
print (min_absolute_diff( 6 ))
|
C#
using System;
using System.Collections.Generic;
class Program {
static int MinAbsoluteDiff( int N)
{
HashSet< int > numSet = new HashSet< int >();
for ( int i = 1; i <= N; i++) {
numSet.Add(i);
}
int minDiff = int .MaxValue;
for ( int i = 1; i < Math.Pow(2, N - 1); i++) {
HashSet< int > subset1 = new HashSet< int >();
HashSet< int > subset2 = new HashSet< int >();
for ( int j = 0; j < N; j++) {
if ((i & (1 << j)) != 0) {
subset1.Add(j + 1);
}
else {
subset2.Add(j + 1);
}
}
int sum1 = 0;
foreach ( int num in subset1) { sum1 += num; }
int sum2 = 0;
foreach ( int num in subset2) { sum2 += num; }
int diff = Math.Abs(sum1 - sum2);
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
static void Main()
{
Console.WriteLine(MinAbsoluteDiff(5));
Console.WriteLine(MinAbsoluteDiff(6));
}
}
|
Javascript
<script>
function minAbsoluteDiff(N) {
let numSet = new Set();
for (let i = 1; i <= N; i++) {
numSet.add(i);
}
let minDiff = Infinity;
for (let i = 1; i < Math.pow(2, N - 1); i++) {
let subset1 = new Set();
let subset2 = new Set();
for (let j = 0; j < N; j++) {
if (i & (1 << j)) {
subset1.add(j + 1);
} else {
subset2.add(j + 1);
}
}
let sum1 = [...subset1].reduce((acc, val) => acc + val, 0);
let sum2 = [...subset2].reduce((acc, val) => acc + val, 0);
let diff = Math.abs(sum1 - sum2);
if (diff < minDiff) {
minDiff = diff;
}
}
return minDiff;
}
document.write(minAbsoluteDiff(5));
document.write( "<br>" );
document.write(minAbsoluteDiff(6));
</script>
|
Time complexity: O(2^N)
Space complexity: O(2^N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
28 Nov, 2023
Like Article
Save Article