- Related Questions & Answers
- Python program to list the difference between two lists.
- Program to interleave list elements from two linked lists in Python
- Adding two Python lists elements
- C# program to list the difference between two lists
- Python program to find Intersection of two lists?
- Find minimum difference between any two element in C++
- Program to find smallest difference between picked elements from different lists in C++
- Find the minimum difference between Shifted tables of two numbers in Python
- Python program to find Union of two or more Lists?
- Python program to print all the common elements of two lists.
- C# program to find common values from two or more Lists
- C# program to find Intersection of two lists
- Minimum Index Sum for Common Elements of Two Lists in C++
- Python program to find missing and additional values in two lists?
- Program to find union of two given linked lists in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

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

3

Advertisements