Minimum +2/-2 Pair Moves to Make One Array a Rearrangement of Another
Company: ByteDance
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Overview: A hard array problem: each operation adds 2 to one element and subtracts 2 from another, and you must find the fewest operations that turn an array into a rearrangement of a target array of the same length. It tests reasoning about what the operation can and cannot change, optimal matching between the arrays, and counts beyond 32-bit range.
Read the full ByteDance Machine Learning Engineer interview experience this question came from
Constraints
- 1 <= n <= 10^5, where n = len(nums) = len(target)
- 1 <= nums[i], target[i] <= 10^6
- nums can always be made similar to target with the operation above.
- The answer can exceed 2^31 - 1 (it stays below 2.5 * 10^10); return it as an exact integer (long in Java, long long in C++).
Examples
Input: ([9, 4, 3], [5, 7, 4])
Expected Output: 1
Explanation: Source example 1: odd values [3, 9] pair with [5, 7] and even [4] with [4]; total difference 4, so 1 operation.
Input: ([2, 10, 5], [6, 9, 2])
Expected Output: 2
Explanation: Source example 2: odd [5] vs [9] differs by 4 and even [2, 10] vs [2, 6] by 4; total 8, so 2 operations.
Hints
- Only the final multiset matters, so think about which value of nums should end up as which value of target.
- Ask what a single operation preserves, both about each individual value and about the array as a whole.
- Each operation moves exactly 2 units up at one position and 2 units down at another; relate the total amount that has to move to the number of operations.