MediumNo. 0822

Card Flipping Game — LeetCode 822 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table
Reading time
2 min

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)where n is the length of the arrays

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

Related problems
No.ProblemDifficulty
0823Binary Trees With FactorsMedium
0820Short Encoding of WordsMedium
0819Most Common WordEasy
0817Linked List ComponentsMedium
0815Bus RoutesHard
0001Two SumEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.