VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-lcm-of-all-pairs-in-a-given-array/

⇱ Minimum LCM of all pairs in a given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum LCM of all pairs in a given array

Last Updated : 15 Jul, 2025

Given an array arr[] of size N, the task is to find the minimum LCM (Least Common Multiple) of all unique pairs in the given array, where 1 <= N <= 105, 1 <= arr[i] <= 105.

Examples: 

Input: arr[] = {2, 4, 3} 
Output:
Explanation 
LCM (2, 4) = 4 
LCM (2, 3) = 6 
LCM (4, 3) = 12 
Minimum possible LCM is 4.

Input: arr [] ={1, 5, 2, 2, 6} 
Output:

Naive Approach  

  1. Generate all possible pairs and compute LCM for every unique pair.
  2. Find the minimum LCM from all unique pairs.

Below is the implementation of the above approach:


Output: 
4

 

Time Complexity: O(N2)
Auxiliary Space: O(log(Ai)), where Ai is the second maximum element in the array.

Efficient Approach: This approach depends upon the formula:  

Product of two number = LCM of two number * GCD of two number 

  1. In the formula of LCM, the denominator is the GCD of two numbers, and the GCD of two numbers will never be greater than the number itself.
  2. So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array.
  3. Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer.
  4. Finally, use a sieve to find the minimum two number that is the multiple of the chosen GCD.

Below is the implementation of the above approach:

Output: 
4

 

Time Complexity: O((N + M) * log(M)) 
Auxiliary Space: O(M) where M is the maximum element in the array.


 

Comment
Article Tags: