Difficulty: Easy | Acceptance: 82.90% | Paid: No Topics: Array
You are given two integer arrays nums1 and nums2.
From nums1, we select an index i and an integer x and add x to nums1[i].
Return the integer x such that the array nums1 is equal to nums2 after adding x to every element of nums1.
It is guaranteed that such an integer x exists.
- Examples
- Constraints
- Direct Calculation
- Iterative Verification
Examples
Example 1
Input:
nums1 = [2,6,4], nums2 = [9,7,5]
Output:
3
Explanation: The integer added to each element of nums1 is 3.
Example 2
Input:
nums1 = [10], nums2 = [5]
Output:
-5
Explanation: The integer added to each element of nums1 is -5.
Example 3
Input:
nums1 = [1,1,1,1], nums2 = [1,1,1,1]
Output:
0
Explanation: The integer added to each element of nums1 is 0.
Examples
Example 1:
Input: nums1 = [2,6,4], nums2 = [9,13,11]
Output: 7
Explanation: 2 + 7 = 9, 6 + 7 = 13, 4 + 7 = 11.
Every element in nums1 plus 7 equals the corresponding element in nums2.
Example 2:
Input: nums1 = [10], nums2 = [5]
Output: -5
Explanation: 10 + (-5) = 5.
Example 3:
Input: nums1 = [1,1,1,1], nums2 = [1,1,1,1]
Output: 0
Explanation: 1 + 0 = 1.
Constraints
n == nums1.length == nums2.length
1 <= n <= 100
0 <= nums1[i], nums2[i] <= 1000
The test cases are generated such that there is an integer x.
Direct Calculation
Intuition
Since the problem guarantees that an integer x exists such that adding x to every element of nums1 results in nums2, the difference between any corresponding pair of elements in nums2 and nums1 must be equal to x. Therefore, we can simply calculate the difference between the first elements of the two arrays.
Steps
- Return
nums2[0] - nums1[0].
Complexity
- Time: O(1)
- Space: O(1)
- Notes: This is the most optimal solution as it requires constant time and space.
Iterative Verification
Intuition Even though the problem guarantees a solution exists, we can verify the result by calculating the difference for the first pair and then iterating through the rest of the array to ensure the difference is consistent. This approach is robust and handles cases where the input might not strictly adhere to the guarantee (though not required for this specific problem).
Steps
- Calculate
xasnums2[0] - nums1[0]. - Iterate through the arrays from index 1 to the end.
- If
nums2[i] - nums1[i]is not equal tox, the input is invalid (but per problem constraints, this won’t happen). - Return
x.
Complexity
- Time: O(n)
- Space: O(1)
- Notes: While this approach is safer in general, it is less efficient than the direct calculation approach for this specific problem due to the guarantee provided.