Bingo Candies – Codeforces Round 1086 (Div. 2) Writeup

Problem Summary
Alice has an board filled with colored candies. Each cell contains a candy of some color . Bob wants to know if he can rearrange the candies so that no row or column has all candies of the same color.
We are given multiple test cases, and for each, we need to determine if such a rearrangement is possible.
Constraints:
- test cases
- (sum of all )
- Colors are integers from 1 to
Output:
Print "YES" if a valid rearrangement exists, "NO" otherwise.
Observations
Let be the color with the maximum number of candies, denoted .
Key observation:
- The answer is YES if and only if .
- If , there are fewer than candies of other colors. With rows, at least one row will be filled entirely with color → violates the rules.
- If , we can always construct a valid board (proof below).
Construction Idea
-
If :
- No color has enough candies to fill a row or column.
- We can arrange candies arbitrarily.
-
Otherwise, :
- Place candies of color along the main diagonal: .
- Take candies not of color and place them along the “wrap-around diagonal”: .
- Place the remaining candies arbitrarily.
Result: Each row and column contains at least two colors, satisfying the constraints.
Step-by-Step Solution

-
Read input for test cases.
-
For each test case:
- Count the frequency of each color.
- If any color appears more than →
NO. - Otherwise →
YES.
Example Walkthrough
Input:
331 2 33 1 44 1 231 1 12 3 41 4 331 1 11 1 11 1 2- Test case 1: Max frequency ≤ 6 →
YES. - Test case 2: Max frequency ≤ 6 →
YES. - Test case 3: Color 1 appears 7 (>6) →
NO.
Code Implementation (Python)
t = int(input())
for _ in range(t): n = int(input()) freq = {}
for _ in range(n): row = list(map(int, input().split())) for val in row: freq[val] = freq.get(val, 0) + 1
if max(freq.values()) > n * n - n: print("NO") else: print("YES")Explanation:
- Count occurrences of each color.
- If any color appears more than , print
"NO". - Otherwise, print
"YES".
Complexity Analysis
- Time complexity: → each board cell is visited once.
- Space complexity: → for storing frequency of colors.
Efficient under given constraints.
Takeaways
- This constructive problem reduces to a counting problem.
- Always check frequency limits before attempting complex arrangements.
- Simple counting avoids unnecessary brute-force and gives an elegant solution.