Check if a sorted array can be divided in pairs whose sum is k
Last Updated :
12 Nov, 2023
Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.
Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that requires only O(1) space.
Check if an array can be divided into pairs whose sum is divisible by k
Examples:
Input: arr[] = {1, 3, 3, 5}, k = 6
Output: True
We can divide array into (1, 5) and (3, 3).
Sum of both of these pairs is 6.
Input: arr[] = {2, 5, 5, 5, 5, 8}, k = 10
Output: True
We can divide array into (2, 8), (5, 5) and
(5, 5). Sum of all these pairs is 10.
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to iterate through every element arr[i]. Find if there is another not yet visited element with value (k – arr[i]). If there is no such element, return false. If a pair is found, then mark both elements as visited. Time complexity of this solution is O(n2 and it requires O(n) extra space.
A Better Solution is to use Hashing. Solution given on this post can be easily modified to work. Time complexity of this solution is O9n) but it requires extra space for hash table.
An Efficient Solution is to use Meet in the Middle algorithm discussed in method 1 here.
1) Initialize two index variables
(a) Initialize first to the leftmost index: l = 0
(b) Initialize second the rightmost index: r = n-1
2) Loop while l < r.
(a) If (A[l] + A[r] != k) then return false
(b) Else r--, l++
Below is the implementation of above algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
bool canPairsSorted( int arr[], int n, int k)
{
if (n & 1)
return false ;
int l = 0, r = n-1;
while (l < r)
{
if (arr[l] + arr[r] != k)
return false ;
l++; r--;
}
return true ;
}
int main()
{
int arr[] = {1, 2, 3, 3, 3, 3, 4, 5};
int k = 6;
int n = sizeof (arr)/ sizeof (arr[0]);
canPairsSorted(arr, n, k)? cout << "True" : cout << "False" ;
return 0;
}
|
Java
class GFG {
static boolean canPairs( int arr[], int n, int k) {
if (n == 1 ) {
return false ;
}
int l = 0 , r = n - 1 ;
while (l < r) {
if (arr[l] + arr[r] != k) {
return false ;
}
l++;
r--;
}
return true ;
}
public static void main(String[] args) {
int arr[] = { 1 , 2 , 3 , 3 , 3 , 3 , 4 , 5 };
int k = 6 ;
int n = arr.length;
if (canPairs(arr, n, k)) {
System.out.println( "True" );
} else {
System.out.println( "False" );
}
}
}
|
Python 3
def canPairsSorted(arr, n, k):
if (n & 1 ):
return False ;
l = 0 ; r = n - 1 ;
while (l < r):
if (arr[l] + arr[r] ! = k):
return False ;
l = l + 1 ; r = r - 1 ;
return True
arr = [ 1 , 2 , 3 , 3 , 3 , 3 , 4 , 5 ]
k = 6
n = len (arr)
if (canPairsSorted(arr, n, k)):
print ( "True" )
else :
print ( "False" );
|
C#
using System;
class GFG
{
static bool canPairs( int []arr, int n, int k)
{
if (n == 1)
{
return false ;
}
int l = 0, r = n - 1;
while (l < r)
{
if (arr[l] + arr[r] != k)
{
return false ;
}
l++;
r--;
}
return true ;
}
public static void Main()
{
int []arr = {1, 2, 3, 3, 3, 3, 4, 5};
int k = 6;
int n = arr.Length;
if (canPairs(arr, n, k))
{
Console.Write( "True" );
}
else
{
Console.Write( "False" );
}
}
}
|
Javascript
<script>
function canPairs(arr,n,k) {
if (n == 1) {
return false ;
}
let l = 0, r = n - 1;
while (l < r)
{
if (arr[l] + arr[r] != k) {
return false ;
}
l++;
r--;
}
return true ;
}
let arr = [1, 2, 3, 3, 3, 3, 4, 5];
let k = 6;
let n = arr.length;
if (canPairs(arr, n, k)) {
document.write( "True" );
} else {
document.write( "False" );
}
</script>
|
PHP
<?php
function canPairs(& $arr , $n , $k )
{
if ( $n & 1)
return false;
$l = 0;
$r = $n - 1;
while ( $l < $r )
{
if ( $arr [ $l ] + $arr [ $r ] != $k )
return false;
$l ++;
$r --;
}
return true;
}
$arr = array (1, 2, 3, 3, 3, 3, 4, 5);
$n = 6;
$k = 6;
$n = sizeof( $arr );
if (canPairs( $arr , $n , $k ))
echo ( "True" );
else
echo ( "False" );
?>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach#2: Using HashMap
This approach uses a HashMap to count the frequency of each element in the array. It then traverses the array and checks if the difference between the current element and the target value k is present in the HashMap and has a frequency greater than 0. If yes, it decrements the frequency of the difference element and moves to the next element in the array. If no, it returns False. Finally, if all elements can be paired, it returns True.
Algorihtm
1. Create a HashMap to store the frequency of each element in the array.
2. Traverse the array and for each element, check if the difference between the element and the target value k is. present in the HashMap and has a frequency greater than 0.
3. If yes, decrement the frequency of the difference element and move to the next element in the array.
4. If no, return False.
5. If all elements can be paired, return True.
C++
#include <bits/stdc++.h>
using namespace std;
bool can_be_divided_into_pairs(vector< int > arr, int k)
{
unordered_map< int , int > frequency_map;
for ( int element : arr) {
frequency_map[element]++;
}
for ( int element : arr) {
if (frequency_map[element] > 0) {
int difference = k - element;
if (frequency_map[difference] > 0) {
frequency_map[element]--;
frequency_map[difference]--;
}
else {
return false ;
}
}
}
return true ;
}
int main()
{
vector< int > arr = { 1, 2, 3, 3, 3, 3, 4, 5 };
int k = 6;
if (can_be_divided_into_pairs(arr, k) == 1) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static boolean canBeDividedIntoPairs( int [] arr, int k) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
for ( int element : arr) {
frequencyMap.put(element, frequencyMap.getOrDefault(element, 0 ) + 1 );
}
for ( int element : arr) {
if (frequencyMap.get(element) > 0 ) {
int difference = k - element;
if (frequencyMap.getOrDefault(difference, 0 ) > 0 ) {
frequencyMap.put(element, frequencyMap.get(element) - 1 );
frequencyMap.put(difference, frequencyMap.get(difference) - 1 );
} else {
return false ;
}
}
}
return true ;
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 3 , 3 , 3 , 4 , 5 };
int k = 6 ;
if (canBeDividedIntoPairs(arr, k)) {
System.out.println( "True" );
} else {
System.out.println( "False" );
}
}
}
|
Python3
def can_be_divided_into_pairs(arr, k):
frequency_map = {}
for element in arr:
frequency_map[element] = frequency_map.get(element, 0 ) + 1
for element in arr:
if frequency_map[element] > 0 :
difference = k - element
if difference in frequency_map and frequency_map[difference] > 0 :
frequency_map[element] - = 1
frequency_map[difference] - = 1
else :
return False
return True
arr = [ 1 , 2 , 3 , 3 , 3 , 3 , 4 , 5 ]
k = 6
print (can_be_divided_into_pairs(arr, k))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static bool CanBeDividedIntoPairs( int [] arr, int k)
{
Dictionary< int , int > frequencyMap = new Dictionary< int , int >();
foreach ( int element in arr)
{
if (frequencyMap.ContainsKey(element))
{
frequencyMap[element]++;
}
else
{
frequencyMap[element] = 1;
}
}
foreach ( int element in arr)
{
if (frequencyMap[element] > 0)
{
int difference = k - element;
if (frequencyMap.ContainsKey(difference) && frequencyMap[difference] > 0)
{
frequencyMap[element]--;
frequencyMap[difference]--;
}
else
{
return false ;
}
}
}
return true ;
}
public static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 3, 3, 3, 4, 5 };
int k = 6;
if (CanBeDividedIntoPairs(arr, k))
{
Console.WriteLine( "True" );
}
else
{
Console.WriteLine( "False" );
}
}
}
|
Javascript
function can_be_divided_into_pairs(arr, k) {
let frequency_map = {};
for (let element of arr) {
frequency_map[element] = (frequency_map[element] || 0) + 1;
}
for (let element of arr) {
if (frequency_map[element] > 0) {
let difference = k - element;
if (difference in frequency_map && frequency_map[difference] > 0) {
frequency_map[element] -= 1;
frequency_map[difference] -= 1;
} else {
return false ;
}
}
}
return true ;
}
let arr = [1, 2, 3, 3, 3, 3, 4, 5];
let k = 6;
console.log(can_be_divided_into_pairs(arr, k));
|
Time Complexity: O(n), where n is the length of the array.
Auxiliary Space: O(n), for the HashMap.
Similar Reads
Check if a given array can be divided into pairs with even sum
Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into pairs such that the sum of each pair is even. If it is possible, print "Yes". Otherwise, print "No". Examples: Input: arr[] = {3, 2, 1, 4, 7, 5, }Output: YesExplanation:The given arr
6 min read
Count pairs in array whose sum is divisible by K
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K. Note: This question is a generalized version of this Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explanation : There are five pairs possible whose sum
10 min read
Count pairs in array whose sum is divisible by 4
Given a array if 'n' positive integers. Count number of pairs of integers in the array that have the sum divisible by 4. Examples : Input: {2, 2, 1, 7, 5}Output: 3Explanation:Only three pairs are possible whose sumis divisible by '4' i.e., (2, 2), (1, 7) and (7, 5)Input: {2, 2, 3, 5, 6}Output: 4Reco
10 min read
Check if an array of 1s and 2s can be divided into 2 parts with equal sum
Given an array containing N elements, each element is either 1 or 2. The task is to find out whether the array can be divided into 2 parts such that the sum of elements in both parts is equal. Examples: Input : N = 3, arr[] = {1, 1, 2}Output : YESInput : N = 4, arr[] = {1, 2, 2, }Output : NOThe idea
13 min read
Count pairs in Array whose product is divisible by K
Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j. Examples: Input: vec = {1, 2, 3, 4, 5, 6}, K = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
11 min read
Check if given Array can be grouped into N/2 pairs with equal sum
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: TrueExplanation: Consider the pairs {1, 6}, {5, 2} and {4, 3}. All 3 of them are having sum = 7. Hen
11 min read
Count of pairs in Array whose product is divisible by K
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K. Examples : Input: A[] = [1, 2, 3, 4, 5], K = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
9 min read
Check If Array Pair Sums Divisible by k
Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k. Examples: Input: arr[] = [9, 7, 5, 3], k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these
15 min read
Check whether a given array is a k sorted array or not
Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
12 min read
Check if an array can be split into subarrays with GCD exceeding K
Given an array arr[] of N integers and a positive integer K, the task is to check if it is possible to split this array into distinct contiguous subarrays such that the Greatest Common Divisor of all elements of each subarray is greater than K. Note: Each array element can be a part of exactly one s
5 min read