LeetCode Solutions
822. Card Flipping Game
Time: $O(n)$ Space: $O(n)$
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;
}
};
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;
}
}
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])