- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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

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

- Related Questions & Answers
- Python program to list the difference between two lists.
- Program to interleave list elements from two linked lists in Python
- Python program to find difference between two timestamps
- 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++
- Python program to find Cartesian product of two lists
- Find the minimum difference between Shifted tables of two numbers in Python
- Python program to print all the common elements of two lists.
- Python program to find Union of two or more Lists?
- C# program to find common values from two or more Lists
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers
- C# program to find Intersection of two lists

Advertisements