Video
Making Mexes
Read the guideFor target mex x, count the copies of x and the missing values below x. The larger count is the answer.
The mex is the first missing number when counting from zero. To make the mex equal x, every number from 0 to x−1 must be present and every copy of x must be removed.
One edit can do two jobs
Changing a copy of x into a missing smaller value both removes an x and fills a gap. If x occurs a times and b smaller values are missing, the answer is max(a, b).
Turn any remaining copies of x into values above x. For any remaining gaps, use entries above x or duplicate copies of smaller values. Since x≤N, there are enough positions after reserving one copy of each smaller value already present.
Compare three targets on the same input
| Target x | Copies of x | Missing below x | Minimum edits |
|---|---|---|---|
| 1 | 0 | None | 0 |
| 2 | 3 | 1 | 3 |
| 3 | 0 | 1 | 1 |
The original array is [2, 2, 2, 0]. From target 0 through 4, the answers are 1, 0, 3, 1, 2, one per line for submission. Start from the original array for every target.
Compute all answers in one scan
Build a frequency table. At target x, missing counts only values strictly below x. Record the answer before adding x to the missing count for the next target.
def min_edits(values):
freq = [0] * (len(values) + 1)
for value in values:
freq[value] += 1
missing = 0
answers = []
for count in freq:
answers.append(max(count, missing))
if count == 0:
missing += 1
return answers
This uses O(N) time and extra space. Test [0, 1, 2] as well. Target 3 needs zero edits.
Official USACO problem and complete sample · Watch the free Bronze lessons.