KatInterview

All MEX Values After One Optional Increment

Arrays & HashingAuto-graded · 29 test cases
HardAuto-gradedArrays & Hashingarraysgreedymath

Last updated

Find every possible MEX after incrementing at most one array element by 1, respecting an upper-bound constraint.

You are given an array values of length n, where each element satisfies 0 <= values[i] <= n - 1. You may perform at most one operation: select an index i where values[i] < n - 1 and increase values[i] by exactly 1.

The MEX (minimum excludant) of an array is the smallest non-negative integer that does not appear in the array.

Return all possible MEX values the array can have after performing zero operations or exactly one operation. Return them in sorted order.

Rules

  • You may perform zero or one operation total. Performing zero operations is always valid, so the MEX of the original array is always reachable.
  • An operation chooses one index i where values[i] < n - 1 and replaces values[i] with values[i] + 1.
  • Any element equal to n - 1 cannot be selected for an operation.
  • Each operation is evaluated independently on the original array; operations do not accumulate.
  • The array may contain duplicate values.

Constraints

  • 1 <= n == len(values) <= 10^5
  • 0 <= values[i] <= n - 1

Examples

Example 1

Input: all_mex_after_increment([0, 1, 2])

Output: [0, 1, 3]

Example 2

Input: all_mex_after_increment([0, 0, 3, 1, 1])

Output: [2, 4]

Example 3

Input: all_mex_after_increment([1, 0, 2, 0])

Output: [1, 2, 3]

Hints

Hint 1

Think about what happens when you increment a value v: you remove one occurrence of v and add one occurrence of v+1. How does this affect the MEX?

Hint 2

The MEX can only change if you remove the last occurrence of a value below the current MEX, or if you fill in the current MEX by incrementing m-1.

Hint 3

You don't need to simulate every possible operation. Group elements by their value and reason about each distinct value's effect on the MEX.