Lexicographically Maximum MEX Array Problem
Description
LeetCode Problem 3948.
You are given an integer array nums.
You want to construct an array result by repeatedly performing the following operation until nums becomes empty:
- Choose an integer
ksuch that1 <= k <= len(nums). - Compute the MEX of the first
kelements ofnums. - Append this MEX to
result. - Remove the first
kelements fromnums.
Return the lexicographically maximum array result that can be obtained after performing the operations.
The MEX of an array is the smallest non-negative integer not present in the array.
An array a is lexicographically greater than an array b if in the first position where a and b differ, array a has an element that is greater than the corresponding element in b. If the first min(a.length, b.length) elements do not differ, then the longer array is the lexicographically greater one.
Example 1:
Input: nums = [0,1,0]
Output: [2,1]
Explanation:
- Take the first k = 2 elements [0, 1] which has MEX = 2. Current result = [2].
- Remaining array [0] has MEX = 1. Thus, the final result = [2, 1].
Example 2:
Input: nums = [1,0,2]
Output: [3]
Explanation:
- Take the first k = 3 elements [1, 0, 2] which has MEX = 3.
- nums is now empty. Thus, the final result = [3].
Example 3:
Input: nums = [3,1]
Output: [0,0]
Explanation:
- Take k = 1, first element [3] has MEX = 0. Current result = [0].
- Remaining array [1] has MEX = 0. Thus, the final result = [0, 0].
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Greedy with Suffix MEX
The first element of the result should be as large as possible. The MEX of a prefix never decreases as the prefix grows, so the largest possible first value is the MEX of the whole remaining array, suf[i]. To keep the rest of the array as long and as large as possible, we take the shortest prefix that already reaches that MEX.
- Precompute
suf[i], the MEX ofnums[i..], by scanning from the right and moving a MEX pointer forward. - From position
i, lettarget = suf[i]. Iftargetis 0, take one element (any longer prefix also gives 0, and a longer result is better). Otherwise scan forward, counting distinct values smaller thantarget, until alltargetof them have been seen. That prefix is the shortest one with MEXtarget; appendtargetand continue after it.
Complexity: O(n) time and O(n) space.
class Solution:
def maximumMEX(self, nums: List[int]) -> List[int]:
n = len(nums)
# suf[i] = mex of nums[i:]
suf = [0] * (n + 1)
seen = [False] * (max(max(nums), n) + 2)
mex = 0
for i in range(n - 1, -1, -1):
seen[nums[i]] = True
while seen[mex]:
mex += 1
suf[i] = mex
ans = []
i = 0
stamp = [-1] * (n + 2)
while i < n:
target = suf[i]
if target == 0:
ans.append(0)
i += 1
continue
need = target
j = i
while need:
v = nums[j]
if v < target and stamp[v] != i:
stamp[v] = i
need -= 1
j += 1
ans.append(target)
i = j
return ans