Leetcode 822. Card Flipping Game
You are given two arrays of integers fronts and backs of the same length. You can choose any card i (0-indexed) and flip it, so that the back of the card becomes the front and vice versa. You need to find the smallest possible number X assigned to the front of a card that isn’t at the back of any card after flipping. If no such number exists, return 0.
Here’s the problem link: Card Flipping Game
fronts and backs have different lengths?
fronts and backs always have the same length as per the problem statement.fronts and backs be negative or zero?
fronts and backs?
The main idea is to identify numbers that appear on both the front and back of the same card because these numbers cannot be the answer as flipping the card doesn’t avoid them.
Here’s the Java code to solve the problem:
import java.util.HashSet;
import java.util.Set;
public class CardFlippingGame {
public int flipgame(int[] fronts, int[] backs) {
Set<Integer> invalidNumbers = new HashSet<>();
// Identify invalid numbers which are the same in front and back of a card.
for (int i = 0; i < fronts.length; i++) {
if (fronts[i] == backs[i]) {
invalidNumbers.add(fronts[i]);
}
}
int minimumNumber = Integer.MAX_VALUE;
for (int i = 0; i < fronts.length; i++) {
if (!invalidNumbers.contains(fronts[i])) {
minimumNumber = Math.min(minimumNumber, fronts[i]);
}
if (!invalidNumbers.contains(backs[i])) {
minimumNumber = Math.min(minimumNumber, backs[i]);
}
}
// If no valid number found, return 0
return minimumNumber == Integer.MAX_VALUE ? 0 : minimumNumber;
}
public static void main(String[] args) {
CardFlippingGame cfg = new CardFlippingGame();
int[] fronts = {1, 2, 4, 4, 7};
int[] backs = {1, 3, 4, 1, 3};
System.out.println(cfg.flipgame(fronts, backs)); // Output should be 2
}
}
n is the length of the fronts and backs arrays.Overall, the time complexity is O(n).
This solution also uses O(n) extra space for storing invalid numbers in a HashSet.
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?