Open In App

Check if given Array can be grouped into N/2 pairs with equal sum

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of integers whose length is N, (where N is even) the task is to check if A[] can be grouped into N/2 pairs having equal sum.

Examples: 

Input: N = 6, A[] = {4, 5, 3, 1, 2, 6}
Output: True
Explanation: Consider the pairs {1, 6}, {5, 2} and {4, 3}. 
All 3 of them are having sum = 7. 
Hence, the given array can be divided into N/2 i.e. 3 pairs having equal sum.

Input : N = 8, A[] = {1, 1, 1, 1, 1, 1, 2, 3}
Output: False

 

Approach: The idea to solve the problem is by using two pointer approach following the below observation.

 If there exist N/2 pairs having equal sum, then the sum of each pair must be equal to min + max, where min is the minimum element of the array and max is the maximum element of the array.

Follow the steps mentioned below to solve the problem based on the above observation:

  • Sort the given array.
  • Initialize a variable (say target) equal to the sum of the first and the last element of the sorted array.
  • Initialize two pointers pointing at the first and the last element.
    • Increment and decrement the pointers simultaneously and check if the sum of elements at the pointers is equal to target.
    • If so, continue iteration.
    • Else return false.
  • After the iteration is complete return true.

Below is the implementation of the above approach.

C++




// C++ code for the above approach.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to divide the given array into
// N/2 pairs having equal sum
bool isPossible(int N, int A[])
{
    // Sorting the given array
    sort(A, A + N);
 
    // Initializing target as the sum of
    // minimum and maximum element
    int target = A[0] + A[N - 1];
 
    // Initializing two pointers
    int i = 0, j = N - 1;
 
    while (i < j) {
 
        // If sum of elements at i and j
        // is equal to target then,
        // increment and decrement i and j
        // respectively
        if (A[i] + A[j] == target) {
            i++;
            j--;
        }
 
        // Else return false
        else {
            return false;
        }
    }
 
    // After whole array is traversed,
    // which means N/2 pairs have sum
    // equal to target, hence return true
    return true;
}
 
// Driver Code
int main()
{
    int N = 6;
    int A[] = { 4, 5, 3, 1, 2, 6 };
 
    // Function call
    bool answer = isPossible(N, A);
    if (answer)
        cout << "True";
    else
        cout << "False";
    return 0;
}


Java




// JAVA code for the above approach.
import java.util.*;
class GFG
{
   
  // Function to check if it is possible
  // to divide the given array into
  // N/2 pairs having equal sum
  public static boolean isPossible(int N, int A[])
  {
    // Sorting the given array
    Arrays.sort(A);
 
    // Initializing target as the sum of
    // minimum and maximum element
    int target = A[0] + A[N - 1];
 
    // Initializing two pointers
    int i = 0, j = N - 1;
 
    while (i < j) {
 
      // If sum of elements at i and j
      // is equal to target then,
      // increment and decrement i and j
      // respectively
      if (A[i] + A[j] == target) {
        i++;
        j--;
      }
 
      // Else return false
      else {
        return false;
      }
    }
 
    // After whole array is traversed,
    // which means N/2 pairs have sum
    // equal to target, hence return true
    return true;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 6;
    int A[] = { 4, 5, 3, 1, 2, 6 };
 
    // Function call
    boolean answer = isPossible(N, A);
    if (answer)
      System.out.print("True");
    else
      System.out.print("False");
  }
}
 
// This code is contributed by Taranpreet


Python3




# Python3 code for the above approach.
 
# Function to check if it is possible
# to divide the given array into
# N/2 pairs having equal sum
def isPossible(N, A):
 
    # Sorting the given array
    A.sort()
 
    # Initializing target as the sum of
    # minimum and maximum element
    target = A[0] + A[N - 1]
 
    # Initializing two pointers
    i = 0
    j = N - 1
 
    while (i < j):
 
        # If sum of elements at i and j
        # is equal to target then,
        # increment and decrement i and j
        # respectively
        if (A[i] + A[j] == target):
            i += 1
            j -= 1
 
        # Else return false
        else:
            return False
 
    # After whole array is traversed,
    # which means N/2 pairs have sum
    # equal to target, hence return true
    return True
 
# Driver Code
N = 6
A = [ 4, 5, 3, 1, 2, 6 ]
 
# Function call
answer = isPossible(N, A)
if (answer):
   print("True")
else:
   print("False")
  
# This code is contributed by shinjanpatra


C#




// C# code for the above approach.
using System;
 
public class GFG{
 
  // Function to check if it is possible
  // to divide the given array into
  // N/2 pairs having equal sum
  static bool isPossible(int N, int[] A){
    // Sorting the given array
    Array.Sort(A);
 
    // Initializing target as the sum of
    // minimum and maximum element
    int target = A[0] + A[N - 1];
 
    // Initializing two pointers
    int i = 0, j = N - 1;
 
    while (i < j) {
 
      // If sum of elements at i and j
      // is equal to target then,
      // increment and decrement i and j
      // respectively
      if (A[i] + A[j] == target) {
        i++;
        j--;
      }
 
      // Else return false
      else {
        return false;
      }
    }
 
    // After whole array is traversed,
    // which means N/2 pairs have sum
    // equal to target, hence return true
    return true;
  }
 
  // Driver Code
  static public void Main (){
 
    int N = 6;
    int[] A = { 4, 5, 3, 1, 2, 6 };
 
    // Function call
    bool answer = isPossible(N, A);
    if (answer == true)
      Console.Write("True");
    else
      Console.Write("False");
  }
}
 
// This code is contributed by hrithikgarg03188.


Javascript




<script>
    // JavaScript code for the above approach.
 
 
    // Function to check if it is possible
    // to divide the given array into
    // N/2 pairs having equal sum
    const isPossible = (N, A) => {
        // Sorting the given array
        A.sort();
 
        // Initializing target as the sum of
        // minimum and maximum element
        let target = A[0] + A[N - 1];
 
        // Initializing two pointers
        let i = 0, j = N - 1;
 
        while (i < j) {
 
            // If sum of elements at i and j
            // is equal to target then,
            // increment and decrement i and j
            // respectively
            if (A[i] + A[j] == target) {
                i++;
                j--;
            }
 
            // Else return false
            else {
                return false;
            }
        }
 
        // After whole array is traversed,
        // which means N/2 pairs have sum
        // equal to target, hence return true
        return true;
    }
 
    // Driver Code
 
    let N = 6;
    let A = [4, 5, 3, 1, 2, 6];
 
    // Function call
    answer = isPossible(N, A);
    if (answer)
        document.write("True");
    else
        document.write("False");
 
// This code is contributed by rakeshsahni
 
</script>


Output

True

Time Complexity: O(N * logN), as we are using inbuilt sort function which will cost O (N*logN).
Auxiliary Space: O(1), as we are not using any extra space.

Approach 2: Using Vectors:

The code above is using a vector approach to solve a specific problem, which is to check if it is possible to divide an array into N/2 pairs having equal sum. The algorithm uses sorting and two pointers to traverse the array and check if there are N/2 pairs that add up to a specific value (target).

Vectors provide iterators that allow you to traverse the elements of the vector in a range-based for loop, making the code more readable and easier to understand.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to divide the given array into
// N/2 pairs having equal sum
bool isPossible(vector<int>& nums)
{
    // Sorting the given array
    sort(nums.begin(), nums.end());
 
    // Initializing target as the sum of
    // minimum and maximum element
    int target = nums[0] + nums[nums.size() - 1];
 
    // Initializing two pointers
    int i = 0, j = nums.size() - 1;
 
    while (i < j) {
 
        // If sum of elements at i and j
        // is equal to target then,
        // increment and decrement i and j
        // respectively
        if (nums[i] + nums[j] == target) {
            i++;
            j--;
        }
 
        // Else return false
        else {
            return false;
        }
    }
 
    // After whole array is traversed,
    // which means N/2 pairs have sum
    // equal to target, hence return true
    return true;
}
 
// Driver Code
int main()
{
    vector<int> nums = {4, 5, 3, 1, 2, 6};
 
    // Function call
    bool answer = isPossible(nums);
    if (answer)
        cout << "True";
    else
        cout << "False";
    return 0;
}


Java




import java.util.*;
 
public class Main {
     
    // Function to check if it is possible
    // to divide the given array into
    // N/2 pairs having equal sum
    public static boolean isPossible(ArrayList<Integer> nums) {
         
        // Sorting the given array
        Collections.sort(nums);
 
        // Initializing target as the sum of
        // minimum and maximum element
        int target = nums.get(0) + nums.get(nums.size() - 1);
 
        // Initializing two pointers
        int i = 0, j = nums.size() - 1;
 
        while (i < j) {
 
            // If sum of elements at i and j
            // is equal to target then,
            // increment and decrement i and j
            // respectively
            if (nums.get(i) + nums.get(j) == target) {
                i++;
                j--;
            }
 
            // Else return false
            else {
                return false;
            }
        }
 
        // After whole array is traversed,
        // which means N/2 pairs have sum
        // equal to target, hence return true
        return true;
    }
 
    // Driver Code
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(4, 5, 3, 1, 2, 6));
 
        // Function call
        boolean answer = isPossible(nums);
        if (answer)
            System.out.println("True");
        else
            System.out.println("False");
    }
}


Python3




from typing import List
 
def is_possible(nums: List[int]) -> bool:
    # Sorting the given array
    nums.sort()
     
    # Initializing target as the sum of
    # minimum and maximum element
    target = nums[0] + nums[-1]
     
    # Initializing two pointers
    i, j = 0, len(nums) - 1
     
    while i < j:
        # If sum of elements at i and j
        # is equal to target then,
        # increment and decrement i and j
        # respectively
        if nums[i] + nums[j] == target:
            i += 1
            j -= 1
        # Else return false
        else:
            return False
     
    # After whole array is traversed,
    # which means N/2 pairs have sum
    # equal to target, hence return true
    return True
 
 
# Driver code
if __name__ == '__main__':
    nums = [4, 5, 3, 1, 2, 6]
     
    # Function call
    answer = is_possible(nums)
    if answer:
        print("True")
    else:
        print("False")


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    // Function to check if it is possible
    // to divide the given array into
    // N/2 pairs having equal sum
    static bool IsPossible(List<int> nums) {
        // Sorting the given array
        nums.Sort();
 
        // Initializing target as the sum of
        // minimum and maximum element
        int target = nums[0] + nums[nums.Count - 1];
 
        // Initializing two pointers
        int i = 0, j = nums.Count - 1;
 
        while (i < j) {
            // If sum of elements at i and j
            // is equal to target then,
            // increment and decrement i and j
            // respectively
            if (nums[i] + nums[j] == target) {
                i++;
                j--;
            }
 
            // Else return false
            else {
                return false;
            }
        }
 
        // After whole array is traversed,
        // which means N/2 pairs have sum
        // equal to target, hence return true
        return true;
    }
 
    // Driver Code
    static void Main() {
        List<int> nums = new List<int> {4, 5, 3, 1, 2, 6};
 
        // Function call
        bool answer = IsPossible(nums);
        if (answer)
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}
// This code is contributed by Prajwal Kandekar


Javascript




// JavaScript Code
 
function isPossible(nums){
  // Sorting the given array
  nums.sort();
   
  // Initializing target as the sum of
  // minimum and maximum element
  let target = nums[0] + nums[nums.length - 1];
   
  // Initializing two pointers
  let i = 0, j = nums.length - 1;
   
  while(i < j){
    // If sum of elements at i and j
    // is equal to target then,
    // increment and decrement i and j
    // respectively
    if(nums[i] + nums[j] === target){
      i += 1;
      j -= 1;
    // Else return false
    } else {
      return false;
    }
  }
   
  // After whole array is traversed,
  // which means N/2 pairs have sum
  // equal to target, hence return true
  return true;
}
 
// Driver code
let nums = [4, 5, 3, 1, 2, 6];
 
// Function call
let answer = isPossible(nums);
if(answer){
  console.log("True");
} else {
  console.log("False");
}


Output

True

Time Complexity: O(N * logN), as we are using inbuilt sort function which will cost O (N*logN).
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads