Leetcode 822. Card Flipping Game
LeetCode Problem 822: Card Flipping Game
On a table, you have cards with the integers fronts
and backs
written on them. A card (i)
has two numbers written on it: fronts[i]
on the front and backs[i]
on the back. We can flip the card so that the number backs[i]
becomes the new front.
You need to choose a card that you can flip such that after one or no flips, the number on the front is not the same as the number on the back.
Return the minimum possible number you can pick to do so. If there is no possible number, return 0
.
fronts
and backs
arrays to find the minimum number that is not in the set of restricted values.#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
int flipgame(std::vector<int>& fronts, std::vector<int>& backs) {
std::unordered_set<int> restricted; // Numbers that are same on both sides of any card
for (size_t i = 0; i < fronts.size(); ++i) {
if (fronts[i] == backs[i]) {
restricted.insert(fronts[i]);
}
}
int min_valid = INT_MAX;
// Check all numbers for potential valid minimum
for (size_t i = 0; i < fronts.size(); ++i) {
if (restricted.find(fronts[i]) == restricted.end()) {
min_valid = std::min(min_valid, fronts[i]);
}
if (restricted.find(backs[i]) == restricted.end()) {
min_valid = std::min(min_valid, backs[i]);
}
}
return (min_valid == INT_MAX) ? 0 : min_valid;
}
int main() {
std::vector<int> fronts = {1, 2, 4, 4, 7};
std::vector<int> backs = {1, 3, 4, 1, 3};
std::cout << "Minimum number you can pick: " << flipgame(fronts, backs) << std::endl;
return 0;
}
The time complexity of this solution is (O(n)), where (n) is the number of cards. The algorithm involves two primary loops:
Thus, the overall complexity is (O(n)).
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?