Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Valid Pairs

Easy
0/40
Average time to solve is 22m
profile
Contributed by
91 upvotes
Asked in companies
AmazonCognizantFacebook

Problem statement

You are given an array 'ARR' of 'N' integers and two integers 'K' and 'M'.

You need to return true if the given array can be divided into pairs such that the sum of every pair gives remainder 'M' when divided by 'K'. Otherwise, you need to return false.

For example:

If the given array is [2, 1, 5, 7] and K = 9 and M = 3. Then you need to return true because we can divide the array into two pairs, i.e (2, 1) and (5, 7) whose sums are 3 and 12, which when divided by 9 gives remainder 3, thus it is possible to divide the given array into pairs.  

Note:

Every element of the array should contribute to only one pair, i.e if the array is [3, 0, 0] and K = 2 and M = 1, then you need to return false, as element 3 will make a pair with any one of the 0. 
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run. 
Then the 'T' test cases follow.

The first line of each test case contains an integer 'N' representing the size of the given array.

The second line contains 'N' single space-separated integers representing the elements of the array 'ARR'.

The third line contains two single space-separated integers 'K' and 'M'.
Output Format :
For each test case, print a single line containing either "True" or "False".
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 10
1 <= N <= 10 ^ 5
1 <= ARR[ i ] <= 10 ^ 9
1 <= K <= 10 ^ 9
0 <= M < K

Where 'N' is the length of the array, 'ARR[ i ]' denotes the 'ith' element of array 'ARR' and 'K' and 'M' are the given integers.

Time Limit: 1 sec
Sample Input 1:
1
4
2 1 5 7
9 3
Sample Output 1:
True
Explanation for input 1:
Pairs will be {2,1} and {5,7} whose sums are 3 and 12 which will give remainder 3 when divided by 9.
Sample Input 2:
1
5
6 6 3 0 0
9 3
Sample Output 2:
False
Explanation for Input 2:
As pairs would be {6, 6} and {3, 0}, but second 0 will not be able to make pair with any of the elements, thus it is not possible to make valid pairs.
Hint

Try to generate all the possible pairs.

Approaches (2)
Brute Force

Approach:  

 

  1. Check the length of the array if it is odd then you can’t make pairs. Thus, return false.
  2. Create a boolean array ‘VISTED’ of length ‘N’ initialized to false, which will store true if the element of the given array at that particular index is paired up already or not.
  3. For each element of the array, try to pair up with each other element of the array.
    1. If both the elements are not paired up i.e(VISITED[i] and VISITED[j] are false), and the sum of both the elements of the array gives remainder ‘M’ when divided by ‘K’, then pair them up by making theirs ‘VISITED’ array true.
    2. Break the iteration as the element is paired up.
  4. Check whether all the elements are paired up or not by checking whether all the elements of the ‘VISITED’ array is true or not, if it is true that means all the elements are paired up, thus return true otherwise return false.
Time Complexity

O(N ^ 2), where ‘N’ is the length of the array.

 

As in the worst case, for each element, we will be running a loop from 0 to N. Therefore, total time complexity would be O(N ^ 2).

Space Complexity

O(N), where ‘N’ denotes the length of ‘ARR’.

 

As in the worst case, an extra space is required for an auxiliary array of size ‘N’. Therefore, total space complexity will be O(N).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Valid Pairs
All tags
Sort by
Search icon

Interview problems

Simple ans easy cpp solution

#include<bits/stdc++.h>
bool isValidPair(vector<int> &arr, int n, int k, int m)
{
    // Write your code here.
    
    if(n%2!=0)  return false;
else{
    unordered_map<int,int>count;
    for(int i=0;i<n;i++)
    {
        count[arr[i]%k]++;
    }

    int first,second;
    for (int i = 0; i < n; i++) {
        first = count[arr[i] % k];
        second = count[(m - arr[i] % k + k) % k];
        if (first != second)
          return false;
    }
    return true;
}
}
6 views
0 replies
0 upvotes

Interview problems

Valid Pairs

def isValidPair(arr, n, k, m):
    if n % 2 == 0:
        # Create a dictionary to count the remainders
        remainder_counts = {}
        
        # Iterate through the array and count the remainders when divided by K
        for num in arr:
            remainder = num % k
            # Update the count for this remainder
            remainder_counts[remainder] = remainder_counts.get(remainder, 0) + 1
        
        # Check if each remainder has a corresponding complement to form pairs
        for remainder, count in remainder_counts.items():
            complement = (m - remainder) % k
            if remainder == complement:
                # If the remainder is its own complement, we need an even count of such remainders
                if count % 2 != 0:
                    return False
            else:
                # Check if the complement exists and has the same count
                if remainder_counts.get(complement, 0) != count:
                    return False
        
        return True


    return False

python

66 views
0 replies
0 upvotes

Interview problems

5/6 test cases passed

def isValidPair(arr, n, k, m):

    if n % 2 != 0:

        return False

 

    remainders = {}

    

    for num in arr:

        rem = num % k

        if rem in remainders:

            remainders[rem] += 1

        else:

            remainders[rem] = 1

 

    for rem, count in remainders.items():

        # Handle the case where m is 0

        if m == 0:

            if rem == 0 and count % 2 != 0:

                return False

            continue

 

        complement = (m - rem + k) % k

        if complement not in remainders:

            return False

        if remainders[complement] != count:

            return False

 

    return True

110 views
0 replies
0 upvotes

Interview problems

three test cases passed... O(n^2) time complexity

def isValidPair(arr, n, k, m):

    a = []

    # Write your code here.

    if (n%2) != 0:

        return False

    for i in range(0,len(arr)):

        for j in range(i+1,len(arr)):

            if arr[i] == -1 or arr[j]==-1:

                pass

            elif (arr[i]+arr[j])%k == m:

                arr[i] = -1

                arr[j] = -1

    for i in range(0,len(arr)):

        if arr[i] != -1:

            return False

    return True

            

    

71 views
0 replies
1 upvote

Interview problems

easy and simple c++ solution

#include<unordered_map>
bool isValidPair(vector<int> &arr, int n, int k, int m)
{
    // Write your code here.
    if(n%2!=0){
        return false;
    }
     unordered_map<int,int> count;
    for(int i=0;i<n;i++){
        count[arr[i]%k]++;
    }
    int first,second;
    for(int i=0;i<n;i++){
        first = count[arr[i]%k];
        second = count[(m-arr[i]%k+k)%k];
        if(first!=second){
            return false;
        }
    }
    return true;
}

beginners

programming

datastructures

554 views
0 replies
2 upvotes

Interview problems

Test case 3 is wrong

Wrong output attached to test cases

49 views
0 replies
0 upvotes

full stack developer

coding

91 views
0 replies
0 upvotes

Interview problems

c++ solution

#include<bits/stdc++.h>
bool isValidPair(vector<int> &arr, int n, int k, int m)
{
    // if n is odd then pair cant be made.
    if(n%2 !=0){
        return false;
    }
    unordered_map<int,int>mp;
    /* find the remainder on dividing each array element and store
    the frequency of reaminders*/ 
    for(int i = 0;i<n; i++){
        mp[arr[i]%k]++;
        
    }

    /*lets suppose a kind of  elment of array gives remainder (m-3) when divided by k.
    then, if there exist an another kind of element which gives remainder 3 when divided by k.
    In this case adding both  kind of element will give remainder m.
    
    no of first kind elements should be equal be equal to the second kind. */ 


    
    int noOf1stKind,noOf2ndkind;
    for(int i = 0; i<n;i++){
        noOf1stKind = mp[arr[i]%k];
        
        if(arr[i]%k <=m){
            noOf2ndkind = mp[m-arr[i]%k];
        }
        else{
            noOf2ndkind= mp[k-(arr[i]%k) +m];
        }
        if(noOf1stKind!=noOf2ndkind)
            return false;
    }
    return true;
    
}
539 views
0 replies
3 upvotes

Interview problems

java Solution

import java.util.HashMap;

import java.util.Map;


 

public class Solution {

public static boolean isValidPair(int[] arr, int n, int k, int m) {

if (n % 2 != 0) {

return false;

}


 

Map<Integer, Integer> map = new HashMap<>();


 

for (int i = 0; i < n; i++) {

int remainder = arr[i] % k;

map.put(remainder, map.getOrDefault(remainder, 0) + 1);

}


 

for (int i = 0; i < n; i++) {

int value = (m - arr[i] % k + k) % k;


 

if (map.containsKey(value)) {

int frequency = map.get(value);

if (frequency > 0) {

map.put(value, frequency - 1);

} else {

return false;

}

} else {

return false;

}

}


 

return true;

}

}


 

273 views
0 replies
2 upvotes

Interview problems

java time complexity is o(n)

import java.util.*;

public class Solution 

{

    public static boolean isValidPair(int[] arr, int n, int k, int m) 

    {

            if(arr.length%2 !=0){

            return false;

        }

        HashMap<Integer,Integer> map = new HashMap<>();

        for(int i=0; i<arr.length; i++){

            if(map.containsKey(arr[i]%k)){

               map.put(arr[i]%k, map.get(arr[i]%k)+1);

 

            }else{

                map.put(arr[i]%k,1);

            }

        }

        

        for(int i =0; i<arr.length; i++){

            int value = m-arr[i]%k;

            if(value < 0){

                value= value+k;

            }

            if(map.containsKey(value)){

                if(map.get(value) >0){

                    

                

                

                map.put(value,map.get(value)-1);

                }else{

                    return false;

                }

 

            }else{

                return false;

            }

        }

        return true;

        

    }

}

296 views
0 replies
0 upvotes
Full screen
Console