Collect All Valid Triples in a Four-Attribute Card Game
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests recognition of a combinatorial validity rule across four ternary attributes and the insight that any two cards uniquely determine the third, reducing O(n³) brute force to O(n²).
Problem
You are working with a deck where every card is described by exactly four properties: hue, figure, count, and fill. Each property takes one of three possible values, encoded as 0, 1, or 2. A card is therefore represented as a list of four integers.
Three cards form a matching triple when, for each of the four properties independently, the three cards' values are either all identical or all distinct. If even one property has two cards sharing a value while the third differs, the triple does not match.
Given a list of cards, return the indices of every matching triple.
Task
Implement the function:
def find_matching_triples(cards: list[list[int]]) -> list[list[int]]:
cards[i] is [hue, figure, count, fill] for card i.
Rules
- Three indices
i < j < kform a matching triple when, for every property indexpin0..3, the multiset{cards[i][p], cards[j][p], cards[k][p]}contains either one distinct value or three distinct values. - Return each matching triple as
[i, j, k]withi < j < k. - The returned list must be sorted in ascending lexicographic order: first by
i, then byj, then byk. - Return an empty list if no matching triple exists, including when fewer than three cards are provided.
Constraints
1 <= len(cards) <= 81len(cards[i]) == 4for everyi, and each element is0,1, or2.- All cards in the input are distinct from one another.
Examples
Example 1
Input: find_matching_triples([[0, 1, 2, 0], [0, 2, 2, 1], [0, 0, 2, 2]])
Output: [[0, 1, 2]]
Example 2
Input: find_matching_triples([[0, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 2]])
Output: []
Example 3
Input: find_matching_triples([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [0, 1, 2, 0], [0, 2, 1, 0], [1, 0, 0, 0]])
Output: [[0, 1, 2], [0, 3, 4]]
Hints
Hint 1
For a single property, the only failing configuration is exactly two cards sharing a value while the third differs — equivalently, a property fails when the sum of its three values is not divisible by 3. Use this to check any triple cheaply.
Hint 2
Once you fix two cards, there is exactly one value for each property that could complete a matching triple: if the two cards agree on a property, the third must match them; if they differ, the third must be the one remaining value (since 0+1+2=3, that value is 3 minus the sum of the two you have). This means any two cards determine their unique potential partner.
Hint 3
Build a lookup table from card tuple to index before iterating over pairs. For each pair (i, j), compute the required partner card, check the table, and only record a triple when the partner's index k satisfies k > j. This last condition eliminates duplicates and keeps indices ordered without any extra bookkeeping.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking whether three cards match
For a single property with values in {0, 1, 2}, there are only two passing configurations:
- All three values equal: sum is
3v ≡ 0 (mod 3). - All three values distinct: sum is
0 + 1 + 2 = 3 ≡ 0 (mod 3).
The only failing case — two values equal, one different — produces a sum that is not divisible by 3. So three cards form a matching triple if and only if every property's sum is a multiple of 3. This mod-3 test is a clean O(1) check per property.
From O(n³) to O(n²): two cards force the third
The key observation is that for any two cards a and b, there is exactly one card that could complete a matching triple with them:
- If
a[p] == b[p], the third card must also have valuea[p](all-equal). - If
a[p] != b[p], the third value must be whichever of{0, 1, 2}is not yet represented, which equals3 - a[p] - b[p].
This gives a deterministic "required partner" for every ordered pair. The algorithm becomes:
- Build a hash map from each card (as a tuple) to its index — O(n) time and space.
- Iterate over all pairs
i < j— O(n²) pairs. - For each pair, compute the required partner tuple in O(d) time (d = 4 properties, so O(1)).
- Look it up in the map. If found at index
kandk > j, record[i, j, k].
Why k > j is the right deduplication filter
Any matching triple {i, j, k} with i < j < k will be "discovered" by three pairs: (i, j), (i, k), and (j, k). Only the pair (i, j) produces a completion index k that is larger than both members of the pair. The other two pairs produce a completion whose index is strictly less than their second element, so the k > j guard silently skips them. Each triple is therefore emitted exactly once, with no extra set or sort needed.
Output order
The outer loop increases i and the inner loop increases j. Each pair produces at most one k. Appending in this order naturally produces lexicographic output, so no final sort is required.
Correctness notes
- The computed
needtuple satisfies the matching rule by construction, so every recorded triple is valid (no false positives). - Every valid triple has its two smallest indices visited as a pair, and the map contains all cards, so every valid triple is found (no false negatives).
- The required partner can never coincide with
aorbthemselves because that would requirea == b, which the distinct-cards constraint rules out.
Complexity
- Time: O(n² · d) = O(n²) since d = 4 is a constant. For n = 81 this is 3,240 pair iterations.
- Space: O(n) for the index map, plus O(output size). The maximum number of matching triples for 81 distinct cards is 1,080.
Edge cases
- Fewer than three cards: the inner loop produces no
k > j, so[]is returned. - No valid triple exists: all partner lookups miss or return an index ≤ j, so
[]is returned. - Exactly three cards: the single pair
(0, 1)either finds card 2 or not, answering the basic "do these three match?" question. - A card that belongs to no triple: it simply never appears as a successful partner lookup.
Reference solution
from typing import List
def find_matching_triples(cards: List[List[int]]) -> List[List[int]]:
n = len(cards)
# Map each card tuple to its index for O(1) lookup.
index = {tuple(cd): i for i, cd in enumerate(cards)}
res = []
for i in range(n):
a = cards[i]
for j in range(i + 1, n):
b = cards[j]
# For each property: if a and b agree, the third must match;
# if they differ, the third is the remaining value (3 - sum).
need = tuple(
a[p] if a[p] == b[p] else 3 - a[p] - b[p]
for p in range(4)
)
k = index.get(need)
# Only record when k > j to emit each triple exactly once,
# already in i < j < k order.
if k is not None and k > j:
res.append([i, j, k])
return res