Array Pair Sum Divisibility Problem Geeks solution
Problem :
Given an array of integers and a number k, write a function that prints True if given array can be divided into pairs such that sum of every pair is divisible by k.
Idea is to save remainder in a hashmap (key as no. of elements) Check whether the remainder is 0 or remainder is half of k means the number is completely divisible and another same number should also be there so check for it
Check if remainder and k-rem are there with equal numbers
code
import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksolutionc
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
st:
while(t-->0)
{
int n=ab.nextInt();
Map<Integer,Integer> hmap=new HashMap<Integer,Integer>();
hmap.clear();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{ arr[i]=ab.nextInt();
}
int k=ab.nextInt();
if(n%2==1)
{
System.out.println("False");
continue st;
}
for(int i=0;i<n;i++)
{
if(hmap.containsKey(arr[i]%k))
hmap.put(arr[i]%k,hmap.get(arr[i]%k)+1);
else
hmap.put(arr[i]%k,1);
}
for(int i=0;i<n;i++)
{
int rem=arr[i]%k;
if(rem==0 || 2*rem==k)
{ if(hmap.get(rem)%2==1)
{
System.out.println("False");
continue st;
}}
else if(hmap.get(rem)!=hmap.get(k-rem))
{
System.out.println("False");
continue st;
}
}
System.out.println("True");
}}}
0 Comments:
Post a Comment