Program to find dropped correct sensor value from the faulty list in Python



Suppose we have two lists nums1 and nums2, they are representing sensor metrics. Each list contains unique values, so a ≠ b. One of these two lists are holding accurate sensor metrics but the other one contains faulty. In the faulty list one value, that is not the last value was dropped and a wrong value was placed to the end of that list. We have to find the actual value that was dropped.

So, if the input is like nums1 = [5, 10, 15] nums2 = [10, 15, 8], then the output will be 5, as first list nums1 holds the actual values = [5, 10, 15], in the second array, that is dropped and 8 is inserted at the end.

To solve this, we will follow these steps −

  • low := 0
  • high :=
  • size of nums1 - 1
  • while low < high, do
    • mid := floor of (low + high) / 2
    • if nums1[mid] is same as nums2[mid], then
      • low := mid + 1
    • otherwise,
      • high := mid
  • return nums1[low] if nums1[low + 1] is same as nums2[low] otherwise nums2[low]

Example

Let us see the following implementation to get better understanding −

def solve(nums1, nums2):
   low, high = 0, len(nums1) - 1

   while low < high:
      mid = (low + high) // 2
      if nums1[mid] == nums2[mid]:
         low = mid + 1
      else:
         high = mid

   return nums1[low] if nums1[low + 1] == nums2[low] else nums2[low]

nums1 = [5, 10, 15]
nums2 = [10, 15, 8]
print(solve(nums1, nums2))

Input

[5, 10, 15], [10, 15, 8]

Output

5

Advertisements