Skip to content

822. Card Flipping Game 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int flipgame(vector<int>& fronts, vector<int>& backs) {
    int ans = 2001;
    unordered_set<int> same;

    for (int i = 0; i < fronts.size(); ++i)
      if (fronts[i] == backs[i])
        same.insert(fronts[i]);

    for (const int f : fronts)
      if (!same.count(f))
        ans = min(ans, f);

    for (const int b : backs)
      if (!same.count(b))
        ans = min(ans, b);

    return ans == 2001 ? 0 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int flipgame(int[] fronts, int[] backs) {
    int ans = 2001;
    Set<Integer> same = new HashSet<>();

    for (int i = 0; i < fronts.length; ++i)
      if (fronts[i] == backs[i])
        same.add(fronts[i]);

    for (final int f : fronts)
      if (!same.contains(f))
        ans = Math.min(ans, f);

    for (final int b : backs)
      if (!same.contains(b))
        ans = Math.min(ans, b);

    return ans == 2001 ? 0 : ans;
  }
}
1
2
3
4
5
class Solution:
  def flipgame(self, fronts: List[int], backs: List[int]) -> int:
    same = {f for f, b in zip(fronts, backs) if f == b}
    return min([num for num in fronts + backs
                if num not in same] or [0])