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++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int N, int A[])
{
sort(A, A + N);
int target = A[0] + A[N - 1];
int i = 0, j = N - 1;
while (i < j) {
if (A[i] + A[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
int main()
{
int N = 6;
int A[] = { 4, 5, 3, 1, 2, 6 };
bool answer = isPossible(N, A);
if (answer)
cout << "True" ;
else
cout << "False" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static boolean isPossible( int N, int A[])
{
Arrays.sort(A);
int target = A[ 0 ] + A[N - 1 ];
int i = 0 , j = N - 1 ;
while (i < j) {
if (A[i] + A[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
int N = 6 ;
int A[] = { 4 , 5 , 3 , 1 , 2 , 6 };
boolean answer = isPossible(N, A);
if (answer)
System.out.print( "True" );
else
System.out.print( "False" );
}
}
|
Python3
def isPossible(N, A):
A.sort()
target = A[ 0 ] + A[N - 1 ]
i = 0
j = N - 1
while (i < j):
if (A[i] + A[j] = = target):
i + = 1
j - = 1
else :
return False
return True
N = 6
A = [ 4 , 5 , 3 , 1 , 2 , 6 ]
answer = isPossible(N, A)
if (answer):
print ( "True" )
else :
print ( "False" )
|
C#
using System;
public class GFG{
static bool isPossible( int N, int [] A){
Array.Sort(A);
int target = A[0] + A[N - 1];
int i = 0, j = N - 1;
while (i < j) {
if (A[i] + A[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
static public void Main (){
int N = 6;
int [] A = { 4, 5, 3, 1, 2, 6 };
bool answer = isPossible(N, A);
if (answer == true )
Console.Write( "True" );
else
Console.Write( "False" );
}
}
|
Javascript
<script>
const isPossible = (N, A) => {
A.sort();
let target = A[0] + A[N - 1];
let i = 0, j = N - 1;
while (i < j) {
if (A[i] + A[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
let N = 6;
let A = [4, 5, 3, 1, 2, 6];
answer = isPossible(N, A);
if (answer)
document.write( "True" );
else
document.write( "False" );
</script>
|
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;
bool isPossible(vector< int >& nums)
{
sort(nums.begin(), nums.end());
int target = nums[0] + nums[nums.size() - 1];
int i = 0, j = nums.size() - 1;
while (i < j) {
if (nums[i] + nums[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
int main()
{
vector< int > nums = {4, 5, 3, 1, 2, 6};
bool answer = isPossible(nums);
if (answer)
cout << "True" ;
else
cout << "False" ;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean isPossible(ArrayList<Integer> nums) {
Collections.sort(nums);
int target = nums.get( 0 ) + nums.get(nums.size() - 1 );
int i = 0 , j = nums.size() - 1 ;
while (i < j) {
if (nums.get(i) + nums.get(j) == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList( 4 , 5 , 3 , 1 , 2 , 6 ));
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 :
nums.sort()
target = nums[ 0 ] + nums[ - 1 ]
i, j = 0 , len (nums) - 1
while i < j:
if nums[i] + nums[j] = = target:
i + = 1
j - = 1
else :
return False
return True
if __name__ = = '__main__' :
nums = [ 4 , 5 , 3 , 1 , 2 , 6 ]
answer = is_possible(nums)
if answer:
print ( "True" )
else :
print ( "False" )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static bool IsPossible(List< int > nums) {
nums.Sort();
int target = nums[0] + nums[nums.Count - 1];
int i = 0, j = nums.Count - 1;
while (i < j) {
if (nums[i] + nums[j] == target) {
i++;
j--;
}
else {
return false ;
}
}
return true ;
}
static void Main() {
List< int > nums = new List< int > {4, 5, 3, 1, 2, 6};
bool answer = IsPossible(nums);
if (answer)
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
}
|
Javascript
function isPossible(nums){
nums.sort();
let target = nums[0] + nums[nums.length - 1];
let i = 0, j = nums.length - 1;
while (i < j){
if (nums[i] + nums[j] === target){
i += 1;
j -= 1;
} else {
return false ;
}
}
return true ;
}
let nums = [4, 5, 3, 1, 2, 6];
let answer = isPossible(nums);
if (answer){
console.log( "True" );
} else {
console.log( "False" );
}
|
Time Complexity: O(N * logN), as we are using inbuilt sort function which will cost O (N*logN).
Auxiliary Space: O(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 :
22 Mar, 2023
Like Article
Save Article