Find the Integer Added to Array I - Problem

Imagine you have two arrays of the same length: nums1 and nums2. Here's the twist - every element in nums1 has been modified by adding (or subtracting) the same integer value x to create nums2.

Your mission is to find that magical integer x that was used to transform nums1 into nums2.

Key Point: The arrays are considered equal when they contain the same integers with the same frequencies, but the order doesn't necessarily matter.

Example: If nums1 = [2, 6, 4] and nums2 = [9, 7, 5], then x = 3 because adding 3 to each element in nums1 gives us [5, 9, 7], which contains the same elements as nums2.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [2, 6, 4], nums2 = [9, 7, 5]
โ€บ Output: 3
๐Ÿ’ก Note: Adding 3 to each element in nums1: [2+3, 6+3, 4+3] = [5, 9, 7]. This contains the same elements as nums2 = [9, 7, 5], just in different order.
example_2.py โ€” Negative Difference
$ Input: nums1 = [10, 6, 9], nums2 = [5, 1, 4]
โ€บ Output: -5
๐Ÿ’ก Note: Subtracting 5 from each element in nums1: [10-5, 6-5, 9-5] = [5, 1, 4]. This exactly matches nums2.
example_3.py โ€” Single Element
$ Input: nums1 = [1], nums2 = [7]
โ€บ Output: 6
๐Ÿ’ก Note: With single element arrays, x = 7 - 1 = 6. Adding 6 to nums1[0] gives us nums2[0].

Constraints

  • 1 โ‰ค nums1.length == nums2.length โ‰ค 100
  • -1000 โ‰ค nums1[i], nums2[i] โ‰ค 1000
  • It is guaranteed that there exists an integer x such that nums1[i] + x == nums2[j] for some arrangement

Visualization

Tap to expand
๐Ÿ” Array Transformation Detective๐Ÿ“‹ Original Evidence (nums1)264Unsorted: [2, 6, 4]Sorted: [2, 4, 6]๐Ÿ” Tampered Evidence (nums2)975Unsorted: [9, 7, 5]Sorted: [5, 7, 9]๐ŸŽฏ Pattern DiscoveryAfter sorting, compare corresponding positions:Position 0: 5 - 2 = 3Position 1: 7 - 4 = 3Position 2: 9 - 6 = 3๐Ÿ”“ Case Solved!x = 3+3 shift applied to all
Understanding the Visualization
1
Crime Scene Analysis
We have two sets of evidence - the original (nums1) and the tampered version (nums2)
2
Organize the Evidence
Sort both arrays to match corresponding pieces of evidence
3
Find the Pattern
Compare any pair to discover the systematic shift applied to all evidence
4
Crack the Case
The difference reveals the constant offset used in the transformation
Key Takeaway
๐ŸŽฏ Key Insight: Since every element undergoes the same transformation, sorting both arrays aligns corresponding elements perfectly. We only need to check one pair to discover the universal shift constant!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K Views
Medium Frequency
~8 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