#822

Card Flipping Game

Medium
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking all combinations, we can use sets to track numbers that are facing up and down, allowing us to find the minimum good integer efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set for numbers facing up and another for numbers facing down.
  2. 2Step 2: Iterate through the cards, adding the front numbers to the up set and the back numbers to the down set.
  3. 3Step 3: For each number in the down set, check if it is not in the up set and track the minimum.
solution.py11 lines
1# Full working Python code
2
3def minGoodInteger(fronts, backs):
4    up = set(fronts)
5    down = set(backs)
6    for num in fronts:
7        down.add(num)
8    for num in backs:
9        up.add(num)
10    good_integers = [num for num in down if num not in up]
11    return min(good_integers) if good_integers else 0

Complexity note: We only traverse the arrays a couple of times, leading to linear time complexity. The space complexity is due to the sets storing up and down numbers.

  • 1Understanding how to track numbers efficiently using sets can greatly reduce complexity.
  • 2Recognizing that we only need to check down numbers against up numbers helps streamline the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.