Skip to content
Problem 822 · LeetCode 822(opens in a new tab)

Card Flipping Game

MediumArrays

There are n cards on a table. Card i has the positive number fronts[i] on one side and backs[i] on the other. Each card starts front side up, and you may turn over as many cards as you like, including none.

Once you are done turning cards, a number is good if it is on the hidden side of at least one card and on the visible side of no card. Return the smallest good number you can arrange, or 0 if no arrangement makes any number good.

Example 1

Input:  fronts = [4, 5, 3, 8], backs = [3, 5, 9, 4]
Output: 3
Why:    turn card 2 over; the 3 under card 0 is now hidden everywhere
2 more examples and the constraints

Example 2

Input:  fronts = [6], backs = [6]
Output: 0
Why:    a 6 faces up whichever way the card lies

Example 3

Input:  fronts = [7, 9], backs = [2, 9]
Output: 2
Why:    2 is already face down and nothing shows a 2

Constraints

  • 1 ≤ n ≤ 1,000, and fronts and backs both have length n
  • 1 ≤ fronts[i], backs[i] ≤ 2,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Test each candidateO(n²)
  2. Ban the twins, then take the minO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 cardsVerdict
Test each candidateO(n²)
Passes; repeats the scan
Ban the twins, then take the minO(n)
Best; two passes

n = number of cards.

Edge cases to test

  • Every card is a twin. No number can ever be hidden: return 0.
  • The smallest number is banned. With a 1 on both sides of a card, the answer must skip past 1.
  • A twin and a non-twin share a value. One twin card with 2 bans 2 everywhere, even if another card has 2 on one side only.
  • Answer on a back. Backs count as candidates too, not just fronts.

Common mistakes

  • Only looking at the backs (or fronts) as candidates instead of both sides.
  • Banning a number only on its twin card instead of everywhere.
  • Returning a large sentinel such as 2,001 instead of 0 when nothing is good.

How to talk through it

  1. 1Clarify. Can I flip any subset? Should I return 0 when no number works?
  2. 2Find the real constraint. A card with two different numbers can always be turned to hide x. Only a twin card forces x face up.
  3. 3Give the brute force. For each candidate, scan all cards for a twin: O(n²).
  4. 4Use a set. Collect twins once, then take the smallest number not in the set.
  5. 5Test out loud. Try one twin card, and a case where the smallest number is banned.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?