#3664

Two-Letter Card Game

Medium
ArrayHash TableStringCountingEnumerationHash 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)

Count cards with letter x in both positions and only one position. Use these counts to form pairs efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count cards with x in both positions, and those with x in only the first or second position.
  2. 2Step 2: Form pairs using the counts, maximizing the number of pairs formed.
  3. 3Step 3: Return the total number of pairs.
solution.py15 lines
1def maxPoints(cards, x):
2    cnt1 = defaultdict(int)
3    cnt2 = defaultdict(int)
4    both = 0
5    for card in cards:
6        if card[0] == x and card[1] == x:
7            both += 1
8        elif card[0] == x:
9            cnt1[card[1]] += 1
10        elif card[1] == x:
11            cnt2[card[0]] += 1
12    points = both
13    for c in cnt1:
14        points += min(cnt1[c], cnt2[c])
15    return points

Complexity note: Single pass to count cards, leading to linear time complexity.

  • 1Pairs must differ by one character.
  • 2Count cards strategically to maximize pairs.

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