Check whether it is possible to make both arrays equal by modifying a single element in Python

PythonServer Side ProgrammingProgramming

Suppose we have two arrays nums1 and nums2 and another value k. We have to check whether both arrays can be made equal by modifying any one element from the nums1 in the following way (only once): We can add any value from the range [-k, k] to any element of nums1.

So, if the input is like nums1 = [5,7,11] nums2 = [5,5,11] k = 8, then the output will be True as we can add -2 (in range [-8,8]) with nums1[1] to make it 5 then it will be same as nums2.

To solve this, we will follow these steps −

  • sort the list nums1 and nums2
  • temp := False
  • idx := -1
  • for i in range 0 to size of nums1 - 1, do
    • if nums1[i] is not same as nums2[i], then
      • if temp is true, then
        • return False
      • temp := True
      • idx := i
  • if idx is -1 or |nums1[idx]-nums2[idx]| <= k, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(nums1, nums2, k):

   temp = False

   idx = -1
   for i in range(len(nums1)):
      if nums1[i] != nums2[i]:
         if temp:
           return False
         temp = True
         idx = i

   if idx == -1 or abs(nums1[idx]-nums2[idx]) <= k:
      return True
   return False

nums1 = [5,7,11]
nums2 = [5,5,11]
k = 8
print(solve(nums1, nums2, k))


[5,7,11], [5,5,11], 8


Updated on 16-Jan-2021 04:35:12