Card Flipping Game — LeetCode 822 Python Solution
- Problem
- #822
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
- Output
- 2
- Explanation
- If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].
Python solution
class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
s = {a for a, b in zip(fronts, backs) if a == b}
return min((x for x in chain(fronts, backs) if x not in s), default=0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the arrays auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 822. Card Flipping Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 822. Card Flipping Game?
- LeetCode 822. Card Flipping Game is rated Medium on LeetCode.
- What is the time complexity of LeetCode 822. Card Flipping Game?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 822. Card Flipping Game?
- The Python solution on this page uses O(n), where n is the length of the arrays auxiliary space.
- What topics does LeetCode 822. Card Flipping Game cover?
- LeetCode 822. Card Flipping Game is tagged Array and Hash Table on LeetCode.