Wednesday, July 24, 2024

[LeetCode] Card Flipping Game

Problem: You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).

After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.

Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0.

Example:

Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
Explanation:
If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].
2 is the minimum good integer as it appears facing down but not facing up.
It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.
Input: fronts = [1], backs = [1]
Output: 0
Explanation:
There are no good integers no matter how we flip the cards, so we return 0.


Approach: The problem description is little confusing but if you don't look at like a game instead you just look at the problem, you will understand a fact that if 

fronts[i] = backs[i]

then this number can' be a good integer as no matter how many times you flip the card the number will always be facing up. Other than these kind of integers, all other integers in both the arrays are good integers. We just need to find the minimum of these integers.

We can use HashSet to store all the not good integers in one iteration and in the second iteration we can get the minimum of all the good integers.


Implementation in C#:

    public int Flipgame(int[] fronts, int[] backs)
    {
        int length = fronts?.Length ?? 0;
        if (length  == 0)
        {
            return 0;
        }
        HashSet<int> sameFacesSet = new HashSet<int>();
        for (int i = 0; i < length; ++i)
        {
            if (fronts[i] == backs[i])
            {
                sameFacesSet.Add(fronts[i]);
            }
        }
        int minGoodInt = int.MaxValue;
        for (int i = 0; i < length; ++i)
        {
            if (!sameFacesSet.Contains(fronts[i]))
            {
                minGoodInt = Math.Min(minGoodInt, fronts[i]);
            }
            if (!sameFacesSet.Contains(backs[i]))
            {
                minGoodInt = Math.Min(minGoodInt, backs[i]);
            }
           
        }
        return minGoodInt == int.MaxValue ? 0 : minGoodInt;
    }

Complexity: O(n)


No comments:

Post a Comment