Check if a sorted array can be divided in pairs whose sum is k
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.
Last Updated :
12 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...