Python 0822.py
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
result = invalid = float("inf")
ignore = set()
for a, b in zip(fronts, backs):
# if a == b then it's impossible to keep that number on one side only
if a == b:
ignore.add(a)
for a, b in zip(fronts, backs):
x = min(a, b)
y = max(a, b)
if x not in ignore:
result = min(result, x)
if y not in ignore:
result = min(result, y)
return 0 if result == invalid else result
Difficulty
and has an acceptance rate of about 51% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method flipgame that receives two integer lists, fronts and backs. Each pair of elements at the same index represents the numbers on the two sides of a card. The goal is to find the smallest number that can appear on the visible side of a card after optionally flipping any subset of cards, under the constraint that the chosen number must not appear on both sides of the same card. If no such number exists, the method returns 0.
Key Steps
Initialisation
result = invalid = float("inf")
ignore = set()
Two sentinel values are created: result holds the best candidate found so far, while invalid represents an unattainable high value used for the final check. An empty set ignore is prepared to collect numbers that are disqualified because they appear on both sides of a card.
Identifying Disallowed Numbers
for a, b in zip(fronts, backs):
if a == b:
ignore.add(a)
The loop iterates over each card. When the front and back values are identical, that number cannot be kept on a single side after any sequence of flips, because it would be present on both sides simultaneously. Such numbers are added to the ignore set.
Evaluating All Candidates
for a, b in zip(fronts, backs):
x = min(a, b)
y = max(a, b)
if x not in ignore:
result = min(result, x)
if y not in ignore:
result = min(result, y)
A second pass examines each card again. For each pair, the smaller value x and the larger value y are extracted. Each value is checked against the ignore set. If a value is not ignored, it becomes a candidate, and result is updated to the smallest such candidate encountered so far. By considering both x and y, the algorithm ensures that every number on any side of any card is examined.
Final Result Determination
return 0 if result == invalid else result
If no candidate was found, result remains equal to invalid, and the method returns 0. Otherwise, the smallest admissible number is returned.
Edge Cases Handled
When a card has identical numbers on both sides, the algorithm correctly excludes that number from consideration, preventing an invalid selection. The use of a set for ignore guarantees that duplicate disallowed numbers are stored only once, avoiding redundant checks. If the input lists are empty, the loops execute zero times, leaving result unchanged; the final conditional then returns 0, which aligns with the expectation that no number can be chosen. The method also gracefully handles cases where all numbers are disallowed, again yielding 0.
Performance Optimisations
The code makes a single pass to collect disallowed numbers and a second pass to evaluate candidates, each using zip to traverse the two lists in lockstep. This avoids the overhead of indexing or creating intermediate structures. Storing disallowed numbers in a hash-based set enables constant-time membership tests during the candidate evaluation phase. By computing min and max once per pair, the algorithm reduces the number of comparisons needed to decide which values to test against the ignore set. The use of float("inf") as a sentinel eliminates the need for additional flags or conditional branches to track whether a candidate has been found.
Overall, the implementation efficiently isolates prohibited numbers and then scans for the minimal permissible value with minimal auxiliary storage and constant-time lookups.
ELI5 - Simplified Explanation
Imagine you have a stack of colorful cards with a number written on the front and a number written on the back. Sometimes a card has the same number on both sides, which means that card is a bit tricky. If you see the same number on both sides of any card, that number is forbidden because it is impossible to pick a side without showing that number.
First, look through every card and find those matching ones. Put all those forbidden numbers into a special bag so they are remembered.
After checking all the cards for those forbidden numbers, look through the cards one more time. Focus on the ones that do not have any forbidden numbers on them. Pick the smallest number seen on any of those safe cards. If a small number is found that is not in the forbidden bag, keep track of it to see if it is the smallest one found so far. By the end, the smallest number captured in this way is the winner. If no safe numbers are found, there is no winner at all.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Rust | Python | Java | C# | Go | TS | ||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 884: Uncommon Words from Two Sentences
- problem 781: Rabbits in Forest
- problem 789: Escape The Ghosts
- problem 817: Linked List Components
- problem 840: Magic Squares In Grid
- problem 861: Score After Flipping Matrix
- problem 870: Advantage Shuffle
- problem 904: Fruit Into Baskets
- problem 745: Prefix and Suffix Search
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality