KatInterview

Reachable Smallest Missing Values After a Single Increment

Arrays & HashingAuto-graded · 22 test cases
HardAuto-gradedArrays & Hashingmexcountingcase-analysis

Last updated

Find every possible smallest-missing value of an array after at most one capped +1 edit, using counting and MEX case analysis in linear time.

You are given a list labels of n integers, where every value lies between 0 and n - 1 inclusive. Values may repeat.

The smallest missing value of a list is the smallest non-negative integer that does not appear in it. For example, the smallest missing value of [0, 1, 3] is 2.

You may perform at most one edit on the list. An edit picks a single position whose value is strictly less than n - 1 and increases that value by exactly 1. Values can never exceed n - 1, so an element equal to n - 1 can never be edited.

Return all the values that the smallest missing value of the list could be after performing zero or one edit, as a sorted list.

Rules

  • Doing nothing is a legal choice, so the smallest missing value of the unmodified list is always part of the answer.
  • Every possible edit is considered independently, starting from the original list. Edits never combine.
  • The result contains each value once, in strictly increasing order.
  • If no element can be edited, the result contains only the original smallest missing value.

Constraints

  • 1 <= n <= 2 * 10^5
  • 0 <= labels[i] <= n - 1
  • The intended solution runs in O(n) time. Trying every edit and recomputing the smallest missing value each time takes O(n^2) and is too slow.

Examples

Example 1

Input: reachable_missing_values([0, 2, 1, 2, 4, 0])

Output: [1, 3, 5]

Example 2

Input: reachable_missing_values([0, 1, 2, 3])

Output: [0, 1, 2, 4]

Hints

Hint 1

Let m be the smallest missing value of the original list. Which edited values could possibly change anything at or below m? Edits on elements larger than m cannot matter.

Hint 2

If a value v < m appears exactly once and you increase it, v disappears and everything below v is still present, so the new smallest missing value is exactly v. Remember that elements equal to n - 1 cannot be edited.

Hint 3

The only other way to change the answer is to increase a spare copy of m - 1 (one that has a duplicate), which fills the hole at m. The new answer is then the next value after m that is absent from the original list.