Problem Description
Given two integer arrays nums1 and nums2 containing only 0s and 1s, replace every 0 with an even positive integer and every 1 with an odd positive integer. After the replacement, both arrays must be strictly increasing and each integer can be used at most once across both arrays. The goal is to minimize the maximum integer appearing in either array after the replacements.
Key Insights
- Each 0 must be replaced with an even number and each 1 with an odd number.
- Both arrays must be strictly increasing, which forces every replacement to be larger than the previous one.
- No integer may be reused between the two arrays, so assignments must be coordinated.
- A dynamic programming state can be used to simulate the construction of both arrays simultaneously.
- The DP state tracks the smallest possible “last used number” after processing a given prefix of each array.
- The main challenge is to decide the next valid candidate (ensuring the correct parity) that is greater than the last used number.
Space and Time Complexity
Time Complexity: O(n1 * n2) where n1 and n2 are the lengths of nums1 and nums2 respectively. Space Complexity: O(n1 * n2) for storing the dynamic programming table.
Solution
We use a dynamic programming approach. Define dp[i][j] to be the minimum possible last number used after forming i elements of nums1 and j elements of nums2. We start with dp[0][0] = 0. For every state, if the next element from either array is a 0, we choose the smallest even number greater than the current last number; if it is a 1, we choose the smallest odd number greater than the current last number. We update the state accordingly. The final answer will be found at dp[n1][n2].
The key trick is to compute the next candidate number with the required parity using:
- For even: candidate = (last + 1) if (last + 1) is even, otherwise (last + 2).
- For odd: candidate = (last + 1) if (last + 1) is odd, otherwise (last + 2).
This process inherently guarantees that both arrays maintain a strictly increasing order while ensuring no reuse of numbers.