We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Integer Added to Array I

Number: 3397

Difficulty: Easy

Paid? No

Companies: Bloomberg, Mitsogo


Problem Description

You are given two arrays of equal length, nums1 and nums2. Each element in nums1 has been increased (or decreased) by an integer x, resulting in nums2. The task is to find that integer x. Two arrays are considered equal if they contain the same integers with the same frequencies.


Key Insights

  • The transformation from nums1 to nums2 is done by adding the same integer x to every element.
  • Based on the relation nums2[i] = nums1[i] + x, x can be directly obtained from any single pair of elements, e.g., x = nums2[0] - nums1[0].
  • Optionally, consistency can be verified by checking all pairs, though the problem guarantees a valid x exists.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the arrays. Space Complexity: O(1), as only a few fixed extra memory variables are used.


Solution

The solution involves calculating the difference between the first elements of nums2 and nums1 to obtain x. Since the same integer x is added to every element, this difference holds for every index. Verification over the entire arrays is optional given the problem constraints. This approach uses simple arithmetic and iteration.


Code Solutions

# Python solution
def findTheInteger(nums1, nums2):
    # Calculate the integer x using the first elements of both arrays
    x = nums2[0] - nums1[0]
    # Optional: Verify that every corresponding pair has the same difference x
    for num1, num2 in zip(nums1, nums2):
        if num2 - num1 != x:
            raise ValueError("Inconsistent differences found")
    # Return the computed integer x
    return x

# Example usage:
print(findTheInteger([2, 6, 4], [9, 7, 5]))  # Expected output: 3
← Back to All Questions