LCM of unique elements present in an array

• Last Updated : 14 May, 2021

Given an array arr[] consisting of N positive integers, the task is to find the LCM of all unique elements of the given array. If the array does not contain any unique elements, then print “-1“.

Examples:

Input: arr[] = {1, 2, 1, 3, 3, 4}
Output: 4
Explanation:
The unique elements of the given array are: 2 and 4. Therefore, the LCM of (2, 4) is 4.

Input: arr[] = {1, 1, 2, 2, 3, 3}
Output: -1

Naive Approach: The simplest approach to solve the given problem is to traverse the given array arr[] for each array element arr[i] and check if arr[i] is unique or not. If found to be true, then store it in another array. After traversing for all the elements, print the LCM of the elements present in the newly created array

Time Complexity: O(N2 + N * log(M)), where M is the largest element of the array arr[].
Auxiliary Space: O(N)

Efficient Approach: The above approach can also be optimized by using Hashing for finding the unique elements in the array. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++

 // C++ program for the above approach #include using namespace std; // Function to find GCD of two numbersint findGCD(int a, int b){    // Base Case    if (b == 0)        return a;     // Recursively find the GCD    return findGCD(b, a % b);} // Function to find LCM of two numbersint findLCM(int a, int b){    return (a * b) / findGCD(a, b);} // Function to find LCM of unique elements// present in the arrayint uniqueElementsLCM(int arr[], int N){    // Stores the frequency of each    // number of the array    unordered_map freq;     // Store the frequency of each    // element of the array    for (int i = 0; i < N; i++) {        freq[arr[i]]++;    }     // Store the required result    int lcm = 1;     // Traverse the map freq    for (auto i : freq) {         // If the frequency of the        // current element is 1, then        // update ans        if (i.second == 1) {            lcm = findLCM(lcm, i.first);        }    }     // If there is no unique element,    // set lcm to -1    if (lcm == 1)        lcm = -1;     // Print the result    cout << lcm;} // Driver Codeint main(){    int arr[] = { 1, 2, 1, 3, 3, 4 };    int N = sizeof(arr) / sizeof(arr);     // Function Call    uniqueElementsLCM(arr, N);     return 0;}

Java

 // Java program for the above approachimport java.util.HashMap;import java.util.Map.Entry; class GFG{     // Function to find GCD of two numbersstatic int findGCD(int a, int b){         // Base Case    if (b == 0)        return a;     // Recursively find the GCD    return findGCD(b, a % b);} // Function to find LCM of two numbersstatic int findLCM(int a, int b){    return (a * b) / findGCD(a, b);} // Function to find LCM of unique elements// present in the arraystatic void uniqueElementsLCM(int arr[], int N){         // Stores the frequency of each    // number of the array    HashMap freq = new HashMap();     // Store the frequency of each    // element of the array    for(int i = 0; i < N; i++)    {        freq.put(arr[i],                 freq.getOrDefault(arr[i], 0) + 1);    }     // Store the required result    int lcm = 1;     // Traverse the map freq    for(Entry i : freq.entrySet())    {                 // If the frequency of the        // current element is 1, then        // update ans        if (i.getValue() == 1)        {            lcm = findLCM(lcm, i.getKey());        }    }     // If there is no unique element,    // set lcm to -1    if (lcm == 1)        lcm = -1;     // Print the result    System.out.print(lcm);} // Driver codepublic static void main(String[] args){    int arr[] = { 1, 2, 1, 3, 3, 4 };    int N = arr.length;     // Function Call    uniqueElementsLCM(arr, N);}} // This code is contributed by abhinavjain194

Python3

 # Python3 program for the above approachfrom collections import defaultdict # Function to find GCD of two numbersdef findGCD(a, b):         # Base Case    if (b == 0):        return a     # Recursively find the GCD    return findGCD(b, a % b) # Function to find LCM of two numbersdef findLCM(a, b):     return (a * b) // findGCD(a, b) # Function to find LCM of unique elements# present in the arraydef uniqueElementsLCM(arr, N):     # Stores the frequency of each    # number of the array    freq = defaultdict(int)     # Store the frequency of each    # element of the array    for i in range(N):        freq[arr[i]] += 1     # Store the required result    lcm = 1     # Traverse the map freq    for i in freq:         # If the frequency of the        # current element is 1, then        # update ans        if (freq[i] == 1):            lcm = findLCM(lcm, i)     # If there is no unique element,    # set lcm to -1    if (lcm == 1):        lcm = -1     # Print the result    print(lcm) # Driver Codeif __name__ == "__main__":     arr = [ 1, 2, 1, 3, 3, 4 ]    N = len(arr)         # Function Call    uniqueElementsLCM(arr, N) # This code is contributed by ukasp

C#

 // C# program for the above approach using System;using System.Collections.Generic; class GFG{   // Function to find GCD of two numbersstatic int findGCD(int a, int b){    // Base Case    if (b == 0)        return a;     // Recursively find the GCD    return findGCD(b, a % b);} // Function to find LCM of two numbersstatic int findLCM(int a, int b){    return (a * b) / findGCD(a, b);} // Function to find LCM of unique elements// present in the arraystatic void uniqueElementsLCM(int []arr, int N){    // Stores the frequency of each    // number of the array    Dictionary freq = new Dictionary();     // Store the frequency of each    // element of the array    for (int i = 0; i < N; i++) {        if(freq.ContainsKey(arr[i]))          freq[arr[i]]++;        else            freq.Add(arr[i],1);    }     // Store the required result    int lcm = 1;     // Traverse the map freq    foreach(KeyValuePair kvp in freq) {         // If the frequency of the        // current element is 1, then        // update ans        if (kvp.Value == 1) {            lcm = findLCM(lcm, kvp.Key);        }    }     // If there is no unique element,    // set lcm to -1    if (lcm == 1)        lcm = -1;     // Print the result    Console.Write(lcm);} // Driver Codepublic static void Main(){    int []arr = {1, 2, 1, 3, 3, 4 };    int N = arr.Length;     // Function Call    uniqueElementsLCM(arr, N);}} // This code is contributed by ipg2016107.

Javascript


Output:
4

Time Complexity: O(N * log(M)), where M is the largest element of the array arr[]
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up