LeetCode Problem 822: Card Flipping Game
On each card of a deck, written a unique integer card[i] is written on its front and a unique integer on its back. You can flip the card any number of times you want, but you cannot flip any card that would result in both sides showing the same integer.
A card is flipped if it shows the integer b
on its front but not on its back, and b
is less than any integer that would appear on both the front and the back of any card.
Write a solution that returns the minimum such b
. If no such number exists, return 0
.
1 <= len(front), len(back) <= 1000
and 1 <= card[i] <= 2000
.b
.b
.Here’s a Python function that implements the described strategy:
def flipgame(fronts, backs):
# Identify numbers that appear on both sides of the same card
same_numbers = {fronts[i] for i in range(len(fronts)) if fronts[i] == backs[i]}
# Initialize result as infinity for comparison purposes
result = float('inf')
# Iterate through fronts and backs to find the minimum candidate
for num in fronts + backs:
if num not in same_numbers:
result = min(result, num)
# If result was updated, return it, otherwise return 0
return result if result != float('inf') else 0
# Example usage
fronts = [1, 2, 4, 4, 7]
backs = [1, 3, 4, 1, 3]
print(flipgame(fronts, backs)) # Output: 2
same_numbers
set requires O(n)
time, where n
is the number of cards.fronts + backs
list takes O(2n)
time.Overall, the time complexity is O(n)
for this approach, which is efficient given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?