Card Flipping Game - Problem

You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back.

Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).

After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.

Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0.

Input & Output

Example 1 — Basic Case
$ Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
💡 Note: Numbers 1 and 4 appear on both sides of some cards, so they can't be good. Number 2 only appears on the front of card 1, so we can flip all other cards to hide number 2 completely, making it good.
Example 2 — No Good Numbers
$ Input: fronts = [1], backs = [1]
Output: 0
💡 Note: The only number is 1, which appears on both sides of the same card. It's impossible to make any number good, so return 0.
Example 3 — Multiple Options
$ Input: fronts = [1,2,3], backs = [3,2,1]
Output: 1
💡 Note: Number 2 appears on both sides of card 1 (front=2, back=2), so it can't be good. Numbers 1 and 3 appear on different cards and can be made good. The minimum good number is 1.

Constraints

  • n == fronts.length == backs.length
  • 1 ≤ n ≤ 1000
  • 1 ≤ fronts[i], backs[i] ≤ 2000

Visualization

Tap to expand
Card Flipping Game INPUT 5 Cards (front/back) 1 1 2 3 4 4 4 1 7 3 fronts = [1,2,4,4,7] backs = [1,3,4,1,3] Front (up) Back (down) ALGORITHM STEPS 1 Find Same Numbers If front[i]==back[i], add to "same" set (can't be good) same = {1, 4} 2 Collect Candidates All values from both arrays all = {1,2,3,4,7} 3 Filter Valid Numbers Remove "same" from candidates valid = {2, 3, 7} 4 Find Minimum Return min of valid set min(2, 3, 7) = 2 Time: O(n) | Space: O(n) FINAL RESULT Flip card 1 to show 2 on back Before: 2 front up --> After: 3 back up 2 is now facing down on card 1, and NOT facing up on any card! Output 2 OK - Minimum good integer 1,4 always face up somewhere Key Insight: A number is "bad" (can never be good) only if front[i] == back[i] for some card. In this case, that number will always be face-up no matter how we flip. All other numbers can potentially be made "good" by appropriate flipping. Use a HashSet to track these "same" numbers efficiently. TutorialsPoint - Card Flipping Game | Hash Set Optimization Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
867 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen