Card Flipping Game Problem
Description
LeetCode Problem 822.
You are given n cards, with a positive integer printed on the front and back of each card (possibly different). You can flip any number of cards (possibly zero).
After choosing the front and the back of each card, you will pick each card, and if the integer printed on the back of this card is not printed on the front of any other card, then this integer is good.
You are given two integer array fronts and backs where fronts[i] and backs[i] are the integers printer on the front and the back of the i^th card respectively.
Return the smallest good and integer after flipping the cards. If there are no good integers, return 0.
Note that a flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
Example 1:
Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and the backs are [1,2,4,1,3].
We choose the second card, which has the number 2 on the back, and it is not on the front of any card, so 2 is good.
Example 2:
Input: fronts = [1], backs = [1]
Output: 0
Constraints:
- n == fronts.length
- n == backs.length
- 1 <= n <= 1000
- 1 <= fronts[i], backs[i] <= 2000
Solution
Approach: Exclude Numbers on Both Sides of a Card
Trying every way to flip the cards is 2n options. Instead, look at which numbers can ever be good.
- If some card has the same number
xon its front and its back,xis on a front no matter how that card is flipped. Soxcan never be good. - Every other number
xthat appears on a card can be made good. Pick a card that showsx, and flip it soxis on its back. Every other card that hasxon it hasxon only one side (otherwisexwould be excluded), so flip each of those to putxon the back too. Nowxis on no front.
So the answer is the smallest number in fronts or backs that is not on both sides of the same card, or 0 if there is none.
- Put every
fronts[i]withfronts[i] == backs[i]into a setsame. - Scan all numbers on both sides and keep the smallest one that is not in
same.
The trap is to exclude a number just because it appears on a front somewhere: in fronts = [1, 2], backs = [2, 1], both numbers are on a front, but flipping the first card makes the fronts [2, 2] and the backs [1, 1], so 1 is good.
Complexity: O(n) time and O(n) space, where n is the number of cards.
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
# A number printed on both sides of one card is always on some front: never good.
same = {f for f, b in zip(fronts, backs) if f == b}
best = 0 # 0 means no good number found yet
for x in fronts + backs:
if x not in same and (best == 0 or x < best):
best = x
return best