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.
- Prepare
- Algorithms
- Greedy
- Beautiful Pairs
- Discussions
Beautiful Pairs
Beautiful Pairs
Sort by
recency
|
287 Discussions
|
Please Login in order to post a comment
Here is my c++ solution, you can watch the explanation here : https://youtu.be/coANgIdBKAk
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.
can anyone help me out with this C# code its failing fro one testcase:
public static int beautifulPairs(List A, List B) { HashSet setB = new HashSet(B); int bPairs = 0;
}
Solution of Beautiul Pairs
This worked, but could you also explain how does this logic work ?
1->Initialize a Counter:
->The code starts with a counter (count) set to 0 to keep track of matches.
2->Single Item Check:
->If A has only one item, it immediately returns 0, meaning it skips the rest of the process since there’s only one item to compare.
3->Count Matches:
->For each item in A, the code checks if it also exists in B. ->If a match is found, it adds 1 to count and removes that item from B so it doesn’t get counted again.
4->Adjust the Final Count:
->After counting, the code checks :
=>If count is less than the length of A, meaning not every item in A had a match, it returns count + 1 (adding a little "bonus"). =>If all items in A matched items in B (count == len(A)), it returns len(A) - 1 (reducing the count by one). If count is less than the length of A, meaning not every item in A had a match, it returns count + 1 (adding a little "bonus"). If all items in A matched items in B (count == len(A)), it returns len(A) - 1 (reducing the count by one).
Haskell
The mandatory "must change a value" was kind of bullshit, but otherwise...