DDSA Solutions

822. Card Flipping Game

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

Problem Overview

Card Flipping Game (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Collect all numbers that appear on both sides of the same card (they can

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

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.

Related patterns: Array, Hash Table, Math

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;
    }
}

Was this solution helpful?

Related Problems