Card Flipping Game

medium array hash-set

Problem

Each card has a front number and a back number. After flipping any subset of cards, a number x is 'good' if it appears on the back of some card but not on the front of any card. Return the minimum good number, or 0 if none.

Inputfronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output2
Card 0 has fronts[0]=backs[0]=1 so 1 can never be good. The smallest other number not on a same-card pair is 2.

def flipgame(fronts, backs):
    same = {f for f, b in zip(fronts, backs) if f == b}
    best = float('inf')
    for x in fronts + backs:
        if x not in same:
            best = min(best, x)
    return 0 if best == float('inf') else best
function flipgame(fronts, backs) {
  const same = new Set();
  for (let i = 0; i < fronts.length; i++)
    if (fronts[i] === backs[i]) same.add(fronts[i]);
  let best = Infinity;
  for (const x of fronts) if (!same.has(x)) best = Math.min(best, x);
  for (const x of backs)  if (!same.has(x)) best = Math.min(best, x);
  return best === Infinity ? 0 : best;
}
import java.util.*;
class Solution {
  public int flipgame(int[] fronts, int[] backs) {
    Set<Integer> same = new HashSet<>();
    for (int i = 0; i < fronts.length; i++)
      if (fronts[i] == backs[i]) same.add(fronts[i]);
    int best = Integer.MAX_VALUE;
    for (int x : fronts) if (!same.contains(x)) best = Math.min(best, x);
    for (int x : backs)  if (!same.contains(x)) best = Math.min(best, x);
    return best == Integer.MAX_VALUE ? 0 : best;
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    int flipgame(vector<int>& fronts, vector<int>& backs) {
        unordered_set<int> same;
        for (int i = 0; i < (int)fronts.size(); i++)
            if (fronts[i] == backs[i]) same.insert(fronts[i]);
        int best = INT_MAX;
        for (int x : fronts) if (!same.count(x)) best = min(best, x);
        for (int x : backs)  if (!same.count(x)) best = min(best, x);
        return best == INT_MAX ? 0 : best;
    }
};
Time: O(n) Space: O(n)