Sunday, November 17, 2024
Google search engine
HomeData Modelling & AISplit first N natural numbers into two sets with minimum absolute difference...

Split first N natural numbers into two sets with minimum absolute difference of their sums

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




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
int minAbsDiff(int N)
{
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
 
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
 
    // Traverse first N
    // natural numbers
    for (int i = N; i > 0; i--) {
 
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2) {
            sumSet1 += i;
        }
        else {
            sumSet2 += i;
        }
    }
    return abs(sumSet1 - sumSet2);
}
 
// Driver Code
int main()
{
    int N = 6;
    cout << minAbsDiff(N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
  
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
     
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
  
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
  
    // Traverse first N
    // natural numbers
    for(int i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.abs(sumSet1 - sumSet2);
}
 
// Driver code
public static void main (String[] args)
{
    int N = 6;
     
    System.out.println(minAbsDiff(N));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program to implement
# the above approach
 
# Function to split the first N
# natural numbers into two sets
# having minimum absolute
# difference of their sums
def minAbsDiff(N):
     
    # Stores the sum of
    # elements of set1
    sumSet1 = 0
 
    # Stores the sum of
    # elements of set2
    sumSet2 = 0
 
    # Traverse first N
    # natural numbers
    for i in reversed(range(N + 1)):
         
        # Check if sum of elements of
        # set1 is less than or equal
        # to sum of elements of set2
        if sumSet1 <= sumSet2:
           sumSet1 = sumSet1 + i
        else:
           sumSet2 = sumSet2 + i
       
    return abs(sumSet1 - sumSet2)
 
# Driver Code
N = 6
 
print(minAbsDiff(N))
 
# This code is contributed by sallagondaavinashreddy7


C#




// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
     
    // Stores the sum of
    // elements of set1
    int sumSet1 = 0;
  
    // Stores the sum of
    // elements of set2
    int sumSet2 = 0;
  
    // Traverse first N
    // natural numbers
    for(int i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.Abs(sumSet1 - sumSet2);
}
 
// Driver code
static void Main()
{
    int N = 6;
     
    Console.Write(minAbsDiff(N));
}
}
 
// This code is contributed by divyeshrabadiya07


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
function minAbsDiff(N)
{
     
    // Stores the sum of
    // elements of set1
    var sumSet1 = 0;
 
    // Stores the sum of
    // elements of set2
    var sumSet2 = 0;
 
    // Traverse first N
    // natural numbers
    for(i = N; i > 0; i--)
    {
         
        // Check if sum of elements of
        // set1 is less than or equal
        // to sum of elements of set2
        if (sumSet1 <= sumSet2)
        {
            sumSet1 += i;
        }
        else
        {
            sumSet2 += i;
        }
    }
    return Math.abs(sumSet1 - sumSet2);
}
 
// Driver code
var N = 6;
 
document.write(minAbsDiff(N));
 
// This code is contributed by umadevi9616
 
</script>


Output

1



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++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
int minAbsDiff(int N)
{
    if (N % 4 == 0 || N % 4 == 3) {
        return 0;
    }
    return 1;
}
 
// Driver Code
int main()
{
    int N = 6;
    cout << minAbsDiff(N);
}


Java




// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
    if (N % 4 == 0 || N % 4 == 3)
    {
        return 0;
    }
    return 1;
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 6;
     
    System.out.println(minAbsDiff(N));
}
}
 
// This code is contributed by sallagondaavinashreddy7


Python3




# Python3 program to implement
# the above approach
 
# Function to split the first N
# natural numbers into two sets
# having minimum absolute
# difference of their sums
def minAbsDiff(N):
     
    if (N % 4 == 0 or N % 4 == 3):
        return 0
         
    return 1
 
# Driver Code
N = 6
 
print(minAbsDiff(N))
 
# This code is contributed by sallagondaavinashreddy7


C#




// C# program to implement
// the above approach
using System;
class GFG{
     
// Function to split the first N
// natural numbers into two sets
// having minimum absolute
// difference of their sums
static int minAbsDiff(int N)
{
  if (N % 4 == 0 ||
      N % 4 == 3)
  {
    return 0;
  }
  return 1;
}
 
// Driver Code
public static void Main(String[] args)
{
  int N = 6;
  Console.WriteLine(minAbsDiff(N));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// javascript program to implement
// the above approach   
// Function to split the first N
    // natural numbers into two sets
    // having minimum absolute
    // difference of their sums
    function minAbsDiff(N) {
        if (N % 4 == 0 || N % 4 == 3) {
            return 0;
        }
        return 1;
    }
 
    // Driver Code
     
        var N = 6;
 
        document.write(minAbsDiff(N));
 
// This code contributed by gauravrajput1
</script>


Output

1



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>
 
// Function to calculate the minimum absolute difference of
// two subsets
int minAbsoluteDiff(int N)
{
    // Create a set containing numbers from 1 to N
    std::set<int> numSet;
    for (int i = 1; i <= N; i++) {
        numSet.insert(i);
    }
 
    int minDiff = INT_MAX;
 
    // Generate all possible subsets using bitwise
    // operations
    for (int i = 1; i < std::pow(2, N - 1); i++) {
        std::set<int> subset1, subset2;
 
        // Divide the numbers into two subsets based on the
        // binary representation of i
        for (int j = 0; j < N; j++) {
            if (i & (1 << j)) {
                subset1.insert(j + 1);
            }
            else {
                subset2.insert(j + 1);
            }
        }
 
        // Calculate the absolute difference between the
        // sums of the two subsets
        int sum1 = std::accumulate(subset1.begin(),
                                   subset1.end(), 0);
        int sum2 = std::accumulate(subset2.begin(),
                                   subset2.end(), 0);
        int diff = std::abs(sum1 - sum2);
 
        // Update the minimum difference if a smaller one is
        // found
        if (diff < minDiff) {
            minDiff = diff;
        }
    }
 
    return minDiff;
}
 
int main()
{
    // Example usage and output
    std::cout << minAbsoluteDiff(5)
              << std::endl; // Output: 1
    std::cout << minAbsoluteDiff(6)
              << std::endl; // Output: 1
 
    return 0;
}


Java




import java.util.HashSet;
import java.util.Set;
 
public class MinAbsoluteDiff {
 
    // Function to find the minimum absolute difference between two subsets of {1, 2, ..., N}
    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;
 
        // Iterate through all possible non-empty subsets of {1, 2, ..., N-1}
        for (int i = 1; i < (1 << (N - 1)); i++) {
            Set<Integer> subset1 = new HashSet<>();
            Set<Integer> subset2 = new HashSet<>();
 
            // Partition the numbers into two subsets based on the binary representation of 'i'
            for (int j = 0; j < N; j++) {
                if ((i & (1 << j)) != 0) {
                    subset1.add(j + 1);
                } else {
                    subset2.add(j + 1);
                }
            }
 
            // Calculate the absolute difference between the sums of the two subsets
            int diff = Math.abs(sum(subset1) - sum(subset2));
 
            // Update the minimum difference if 'diff' is smaller
            if (diff < minDiff) {
                minDiff = diff;
            }
        }
 
        return minDiff;
    }
 
    // Function to calculate the sum of elements in a set
    public static int sum(Set<Integer> set) {
        int sum = 0;
        for (int num : set) {
            sum += num;
        }
        return sum;
    }
 
    public static void main(String[] args) {
        // Example usage
        System.out.println(minAbsoluteDiff(5)); // Output: 1
        System.out.println(minAbsoluteDiff(6)); // Output: 1
    }
}


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
 
# Example usage
print(min_absolute_diff(5)) # Output: 1
print(min_absolute_diff(6)) # Output: 1


Output

1
1



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 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments