Skip to content
Related Articles

Related Articles

Minimum score after flipping the cards
  • Difficulty Level : Easy
  • Last Updated : 16 Dec, 2018

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.

Examples:

Input: fronts = [1, 2, 4, 4, 7, 8], backs = [1, 3, 4, 1, 3, 9]
Output: 2
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]
Output: 1



Approach:

  • 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 front array, 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:




# Python3 iomplementation of the approach
import itertools
  
MAX = 9999
  
def flipgame(fronts, backs):
  
    same = {k for i, k in enumerate(fronts) if k == backs[i]}
      
    # Initialize answer to arbitrary value
    ans = MAX
      
    for k in itertools.chain(fronts, backs):
        if k not in same:
            ans = min(ans, k)
  
    # Return final answer
    return ans % MAX
  
# Driver Code
fronts = [1, 2, 4, 4, 7]
backs = [1, 3, 4, 1, 3]
print(flipgame(fronts, backs))
Output:
2

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :