Find the Integer Added to Array I - Problem

You are given two arrays of equal length, nums1 and nums2.

Each element in nums1 has been increased (or decreased in the case of negative) by an integer, represented by the variable x. As a result, nums1 becomes equal to nums2.

Two arrays are considered equal when they contain the same integers with the same frequencies.

Return the integer x.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [2,6,3], nums2 = [5,9,6]
Output: 3
💡 Note: Each element in nums1 increased by 3: [2+3, 6+3, 3+3] = [5,9,6] = nums2
Example 2 — Negative Adjustment
$ Input: nums1 = [10,6,2], nums2 = [5,1,-3]
Output: -5
💡 Note: Each element in nums1 decreased by 5: [10-5, 6-5, 2-5] = [5,1,-3] = nums2
Example 3 — Zero Adjustment
$ Input: nums1 = [1,1,1,1], nums2 = [1,1,1,1]
Output: 0
💡 Note: Arrays are already equal, so x = 0: [1+0, 1+0, 1+0, 1+0] = [1,1,1,1]

Constraints

  • 1 ≤ nums1.length == nums2.length ≤ 1000
  • -1000 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Find the Integer Added to Array I INPUT nums1 (original) 2 6 3 + x nums2 (result) 5 9 6 Input Values: nums1 = [2, 6, 3] nums2 = [5, 9, 6] ALGORITHM STEPS 1 Sort Arrays Sort both nums1 and nums2 2 Find Min Values min(nums1)=2, min(nums2)=5 3 Calculate Difference x = min(nums2) - min(nums1) 4 Compute Result x = 5 - 2 = 3 Direct Calculation: sorted nums1: [2,3,6] sorted nums2: [5,6,9] x = 5 - 2 = 3 FINAL RESULT nums1 + x = nums2 2 +3 = 5 OK 6 +3 = 9 OK 3 +3 = 6 OK Output: x = 3 All elements verified! [2,6,3] + 3 = [5,9,6] Key Insight: Since each element in nums1 is increased by the same value x, the difference between any corresponding elements after sorting will be x. Using minimum values: x = min(nums2) - min(nums1) TutorialsPoint - Find the Integer Added to Array I | Direct Calculation Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~5 min Avg. Time
892 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