Problem Description
We are given two initially empty arrays arr1 and arr2. We need to add positive integers to these arrays such that: • arr1 contains uniqueCnt1 distinct positive integers, none of which is divisible by divisor1. • arr2 contains uniqueCnt2 distinct positive integers, none of which is divisible by divisor2. • No integer appears in both arrays. The goal is to minimize the maximum integer used in either array.
Key Insights
- The challenge can be solved using binary search on the candidate maximum value X.
- For a given X, count numbers in [1, X] that are eligible for arr1 (not divisible by divisor1) and for arr2 (not divisible by divisor2).
- Some numbers are valid for both arrays (i.e. numbers not divisible by either divisor) and can be shared between arr1 and arr2.
- It is best to first assign numbers that are exclusively valid for one array, and then use the common pool to satisfy the remaining requirement.
- Check feasibility by computing: • only1 = numbers valid only for arr1 • only2 = numbers valid only for arr2 • common = numbers valid for both arrays
- Use binary search to find the smallest X such that the common numbers can cover the residual requirements for both arrays.
Space and Time Complexity
Time Complexity: O(log N) where N is the search space for the maximum number (based on the answer). Space Complexity: O(1)
Solution
We use binary search on the candidate maximum integer X. For a given X, calculate:
- common = X - (floor(X/divisor1) + floor(X/divisor2) - floor(X/lcm))
- only1 = (X - floor(X/divisor1)) - common (numbers that are valid only for arr1)
- only2 = (X - floor(X/divisor2)) - common (numbers that are valid only for arr2)
Then, the additional numbers needed: • req1 = max(0, uniqueCnt1 - only1) • req2 = max(0, uniqueCnt2 - only2)
If req1 + req2 ≤ common then X is a feasible candidate. The binary search finds the minimum X which meets these conditions.