Given N cards having positive integers printed on the front and the back of each card (possibly different). Any number of cards can be flipped, and after that we choose one card from the deck. If the number X written on the back of the chosen card is not in the front of any card, then we say number X is good. The task is to find the smallest number that is good. If no number is good, then print 0.
Note: A flip swaps the front and back numbers present on the card i.e. the value on the front is now on the back and vice versa.
Input: fronts = [1, 2, 4, 4, 7, 8], backs = [1, 3, 4, 1, 3, 9]
If we flip the second card, the fronts are [1, 3, 4, 4, 7, 8] and the backs are [1, 2, 4, 1, 3, 9].
Now, we choose the second card, having number 2 on the back, and it isn’t on the front of any other card, so 2 is good.
Input: fronts = [1, 2, 3, 4, 5], backs = [6, 7, 8, 9, 10]
- If a card has the same value K written on the front and the back then K cannot be the answer as no matter how many times you flip the card the result will be the same.
- Every other card that has different numbers written on the front and backs are candidates for the answer as no matter how many times the number K repeats in the
frontarray, just flip all the cards then there will no longer be a card that has K written on the front then we can simply choose any card (minimum) that has K written on it’s back and it is the answer.
- Now the problem reduces to finding all the numbers K1, K2, …, Kn such that they are not repeated on any card and then among all the numbers written on the backs of K1, K2, …, Kn find the minimum.
- If the result is not possible then print 0.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.