We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Exhaustively, this problem can be considered in two cases
A and B are similar. That is, for each item in A, there exists an item in B and there is no unmatched item in A. This directly implies vice-versa. In this case then, you will have to change something in B to something that's not in A. So you count no of paired items and reduce one.
A and B are not similar. That is, there is at least one item in A that doesn't have its correponding pair in B which also implies vice-versa. In this case, you can change any one of those unmatched items in B back to something that already exists in A. So you count no of paired items and add one.
Here is python3 solution. I must add this is not a greedy problem at all. A greedy approach requires making optimal choice at each pass of your solution.
defbeautifulPairs(A,B):# Write your code herefreq_A=Counter(A)#buildafrequencydictionarypaired=0foriinB:iffreq_A[i]>0:paired+=1freq_A[i]-=1common=freq_A.most_common(1)[0]#returnsatupleifcommon[1]>0:#atleastoneunmatchediteminAreturnpaired+1else:#AandBaresimilarreturnpaired-1
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Beautiful Pairs
You are viewing a single comment's thread. Return to all comments →
Exhaustively, this problem can be considered in two cases
A and B are similar. That is, for each item in A, there exists an item in B and there is no unmatched item in A. This directly implies vice-versa. In this case then, you will have to change something in B to something that's not in A. So you count no of paired items and reduce one.
A and B are not similar. That is, there is at least one item in A that doesn't have its correponding pair in B which also implies vice-versa. In this case, you can change any one of those unmatched items in B back to something that already exists in A. So you count no of paired items and add one.
Here is python3 solution. I must add this is not a greedy problem at all. A greedy approach requires making optimal choice at each pass of your solution.