DDSA Solutions

822. Card Flipping Game

Time: O(n)
Space: O(n)
Advertisement

Approach

Collect all numbers that appear on both sides of the same card (they can

never be the chosen number). Then find the minimum value appearing anywhere that is

not in that "same" set.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Hash Table

Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.

Math

Math problems test number theory, combinatorics, and modular arithmetic. Common tools: GCD/LCM (Euclidean algorithm), prime sieve, modular inverse (Fermat's little theorem), digit manipulation, and bit tricks. Overflow is a key concern in C# — use long when products may exceed 2³¹.

822.cs
C#
// Approach: Collect all numbers that appear on both sides of the same card (they can
// never be the chosen number). Then find the minimum value appearing anywhere that is
// not in that "same" set.
// Time: O(n) Space: O(n)
public class Solution
{
    public int Flipgame(int[] fronts, int[] backs)
    {
        const int kMax = 2001;
        int ans = kMax;
        HashSet<int> same = new HashSet<int>();

        for (int i = 0; i < fronts.Length; ++i)
            if (fronts[i] == backs[i])
                same.Add(fronts[i]);

        foreach (int front in fronts)
            if (!same.Contains(front))
                ans = Math.Min(ans, front);

        foreach (int back in backs)
            if (!same.Contains(back))
                ans = Math.Min(ans, back);

        return ans == kMax ? 0 : ans;
    }
}

Advertisement
Was this solution helpful?