Constructing Two Increasing Arrays - Problem

Given 2 integer arrays nums1 and nums2 consisting only of 0 and 1, your task is to calculate the minimum possible largest number in arrays nums1 and nums2, after doing the following.

Replace every 0 with an even positive integer and every 1 with an odd positive integer. After replacement, both arrays should be increasing and each integer should be used at most once.

Return the minimum possible largest number after applying the changes.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [0,1], nums2 = [1]
Output: 3
💡 Note: Replace nums1=[0,1] with [2,3] and nums2=[1] with [1]. Both arrays are increasing and max value is 3.
Example 2 — All Zeros
$ Input: nums1 = [0,0], nums2 = [0]
Output: 6
💡 Note: Replace nums1=[0,0] with [2,4] and nums2=[0] with [6]. All even numbers, max is 6.
Example 3 — All Ones
$ Input: nums1 = [1], nums2 = [1,1]
Output: 5
💡 Note: Replace nums1=[1] with [1] and nums2=[1,1] with [3,5]. All odd numbers, max is 5.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • nums1[i], nums2[i] ∈ {0, 1}

Visualization

Tap to expand
Constructing Two Increasing Arrays INPUT nums1 = [0, 1] 0 1 even odd nums2 = [1] 1 odd Rules: - 0 --> even positive integer - 1 --> odd positive integer - Arrays must be increasing ALGORITHM STEPS 1 Initialize Track last used values 2 Process nums2[0]=1 Assign smallest odd: 1 3 Process nums1[0]=0 Assign smallest even: 2 4 Process nums1[1]=1 Assign odd > 2: 3 Greedy Assignments: nums2: [1] --> [1] nums1: [0,1] --> [2,3] Max value used: 3 FINAL RESULT Transformed Arrays: nums1 result: 2 3 even odd nums2 result: 1 odd Output: 3 [OK] Both arrays increasing Key Insight: Greedy approach: Process both arrays together, always assigning the smallest valid number. For 0s pick next available even; for 1s pick next available odd. Ensure strictly increasing order. The minimum largest number is achieved by using the smallest valid integers at each step. TutorialsPoint - Constructing Two Increasing Arrays | Greedy Assignment
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen