Program to find minimum difference between two elements from two lists in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists L1 and L2, we have to find the smallest difference between a number from L1 and a number from L2.

So, if the input is like L1 = [2, 7, 4], L2 = [16, 10, 11], then the output will be 3, as the smallest difference is 10 - 7 = 3.

To solve this, we will follow these steps −

  • sort the list L1 and sort the list L2
  • ans := infinity
  • i := 0, j := 0
  • while i < size of L1 and j < size of L2, do
    • ans := minimum of ans and |L1[i] - L2[j]|
    • if L1[i] < L2[j], then
      • i := i + 1
    • otherwise,
      • j := j + 1
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, L1, L2):
      L1.sort()
      L2.sort()
      ans = float("inf")
      i = j = 0
      while i < len(L1) and j < len(L2):
         ans = min(ans, abs(L1[i] - L2[j]))
         if L1[i] < L2[j]:
            i += 1
         else:
            j += 1
      return ans
ob = Solution()
L1 = [2, 7, 4] L2 = [16, 10, 11]
print(ob.solve(L1, L2))

Input

[2, 7, 4], [16, 10, 11]

Output

3
raja
Published on 19-Oct-2020 15:34:26
Advertisements