Maximum distinct prime factors of elements in a K-length subarray

Given an array arr[] of N positive integers and an integer K, the task is to find the maximum distinct prime factors in a subarray of length K.
Examples:
Input: arr[] = {5, 9, 14, 6, 10, 77}, K=3
Output: 5
Explanation:Â
The sub-array of length 3 with maximum distinct prime factors is 6, 10, 77 and prime factors are 2, 3, 5, 7, 11.Input: arr[] = {4, 2, 6, 10}, K=3
Output: 3
Explanation:Â
The sub-array of length 3 with maximum distinct prime factors is 2, 6, 10 and prime factors are 2, 3, 5.
Naive Approach: The simplest approach is to generate all possible subarrays of length K and for traverse each subarray and count distinct prime factors of its elements. Finally, print the maximum count of distinct prime factors obtained for any subarray. Time complexity: O(N2 log N)
Auxiliary Space: O(N)
Efficient Approach: The idea is to use the Sliding Window Technique to solve this problem. Follow the steps below:
- Generate and store the smallest prime factor of every element using Sieve.
- Store the distinct prime factors of first K array elements in a Map.
- Traverse the remaining array maintaining the K-length window by adding current element to the previous subarray and removing the first element of the previous subarray
- Find all the prime factors of the newly added element to the subarray and store it in the Map. Subtract the frequency of prime factors of the removed element from the Map.
- After completing the above operations for the entire array, print the maximum Map size obtained for any subarray as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
#define Max 100001Â
// Stores smallest prime// factor for every numberint spf[Max];Â
// Function to calculate smallest// prime factor of every numbervoid sieve(){    // Marking smallest prime factor    // of every number to itself    for (int i = 1; i < Max; i++)        spf[i] = i;Â
    // Separately marking smallest prime    // factor of every even number to be 2    for (int i = 4; i < Max; i = i + 2)        spf[i] = 2;Â
    for (int i = 3; i * i < Max; i++)Â
        // If i is prime        if (spf[i] == i) {Â
            // Mark spf for all numbers divisible by i            for (int j = i * i; j < Max; j = j + i) {Â
                // Marking spf[j] if it is not                // previously marked                if (spf[j] == j)                    spf[j] = i;            }        }}Â
// Function to find maximum distinct// prime factors of subarray of length kint maximumDPF(int arr[], int n, int k){    // Precalculate Smallest    // Prime Factors    sieve();Â
    int ans = 0, num;Â
    // Stores distinct prime factors    // for subarrays of size k    unordered_map<int, int> maps;Â
    // Calculate total prime factors    // for first k array elements    for (int i = 0; i < k; i++) {Â
        // Calculate prime factors of        // every element in O(logn)        num = arr[i];        while (num != 1) {Â
            maps[spf[num]]++;            num = num / spf[num];        }    }Â
    // Update maximum distinct    // prime factors obtained    ans = max((int)maps.size(), ans);Â
    for (int i = k; i < n; i++) {Â
        // Remove prime factors of        // the removed element        num = arr[i - k];        while (num != 1) {Â
            // Reduce frequencies            // of prime factors            maps[spf[num]]--;Â
            if (maps[spf[num]] == 0)Â
                // Erase that index from map                maps.erase(spf[num]);Â
            num = num / spf[num];        }Â
        // Find prime factoes of        // added element        num = arr[i];        while (num != 1) {Â
            // Increase frequencies            // of prime factors            maps[spf[num]]++;            num = num / spf[num];        }Â
        // Update maximum distinct        // prime factors obtained        ans = max((int)maps.size(), ans);    }Â
    return ans;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 4, 2, 6, 10 };Â Â Â Â int k = 3;Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << maximumDPF(arr, n, k) << endl;Â
    return 0;} |
Java
// Java program for the above approachimport java.io.*;import java.util.*;Â
class GFG {Â
    static int Max = 100001;    static int spf[] = new int[Max];Â
    // Function to precalculate smallest    // prime factor of every number    public static void sieve()    {        // Marking smallest prime factor        // of every number to itself.        for (int i = 1; i < Max; i++)            spf[i] = i;Â
        // Separately marking smallest prime        // factor of every even number to be 2        for (int i = 4; i < Max; i = i + 2)            spf[i] = 2;Â
        for (int i = 3; i * i < Max; i++)Â
            // If i is prime            if (spf[i] == i) {Â
                // Mark spf for all numbers divisible by i                for (int j = i * i; j < Max; j = j + i) {Â
                    // Marking spf[j] if it is not                    // previously marked                    if (spf[j] == j)                        spf[j] = i;                }            }    }Â
    // Function to find maximum distinct    // prime factors of subarray of length k    public static int maximumDPF(int arr[], int n, int k)    {        // Precalculate smallest        // prime factor        sieve();Â
        int ans = 0, num;Â
        // Stores distinct prime factors        // for subarrays of size k        Map<Integer, Integer> maps            = new HashMap<Integer, Integer>();Â
        // Calculate total prime factors        // for first k array elements        for (int i = 0; i < k; i++) {Â
            // Calculate prime factors of            // every element in O(logn)            num = arr[i];            while (num != 1) {Â
                maps.put(spf[num],                         maps.getOrDefault(spf[num], 0)                             + 1);                num = num / spf[num];            }        }Â
        // Update maximum distinct        // prime factors obtained        ans = Math.max((int)maps.size(), ans);Â
        for (int i = k; i < n; i++) {Â
            // Remove prime factors of            // the removed element            num = arr[i - k];            while (num != 1) {Â
                // Reduce frequencies                // of prime factors                maps.put(spf[num],                         maps.getOrDefault(spf[num], 0)                             - 1);Â
                if (maps.get(spf[num]) == 0)                    maps.remove(spf[num]);Â
                num = num / spf[num];            }Â
            // Insert prime factors of            // the added element            num = arr[i];            while (num != 1) {Â
                // Increase frequencies                // of prime factors                maps.put(spf[num],                         maps.getOrDefault(spf[num], 0)                             + 1);                num = num / spf[num];            }Â
            // Update maximum distinct            // prime factors obtained            ans = Math.max((int)maps.size(), ans);        }Â
        return ans;    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = { 4, 2, 6, 10 };Â
        int k = 3;        int n = arr.length;Â
        System.out.println(maximumDPF(arr, n, k));    }} |
Python3
# Python program for the above approachimport math as mtÂ
Max = 100001Â
# Stores smallest prime factor for# every numberspf = [0 for i in range(Max)]Â
# Function to precalculate smallest# prime factor of every numberÂ
Â
def sieve():Â
  # Marking smallest prime factor of every    # number to itself.    for i in range(1, Max):        spf[i] = iÂ
    # Separately marking spf for    # every even number as 2    for i in range(4, Max, 2):        spf[i] = 2Â
    for i in range(3, mt.ceil(mt.sqrt(Max))):Â
        # Checking if i is prime        if (spf[i] == i):Â
            # marking SPF for all numbers            # divisible by i            for j in range(i * i, Max, i):Â
                # marking spf[j] if it is                # not previously marked                if (spf[j] == j):                    spf[j] = iÂ
# Function to find maximum # distinct prime factors# of the subarray of length kÂ
Â
def maximumDPF(arr, n, k):Â
    # precalculating Smallest Prime Factor    sieve()Â
    ans = 0Â
    # map to store distinct prime factor    # for subarray of size k    maps = {}Â
    # Calculating the total prime factors    # for first k elements    for i in range(0, k):Â
        # Calculating prime factors of        # every element in O(logn)        num = arr[i]        while num != 1:            maps[spf[num]] = maps.get(                             spf[num], 0)+1            num = int(num / spf[num])Â
    ans = max(len(maps), ans)Â
    for i in range(k, n):               # Perform operation for        # removed element        num = arr[i - k]        while num != 1:Â
            maps[spf[num]] = maps.get(                             spf[num], 0)-1Â
            # if value in map become 0,            # then erase that index from map            if maps.get(spf[num], 0) == 0:                maps.pop(spf[num])Â
            num = int(num / spf[num])Â
        # Perform operation for        # added element        num = arr[i]        while num != 1:Â
            maps[spf[num]] = int(maps.get(                                 spf[num], 0))+1            num = int(num / spf[num])Â
        ans = max(len(maps), ans)Â
    return ansÂ
Â
# Driver Codeif __name__ == '__main__':Â
    # Given array arr    arr = [4, 2, 6, 10]Â
    # Given subarray size K    k = 3    n = len(arr)Â
    # Function call    print(maximumDPF(arr, n, k)) |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
public class GFG {Â
    public static int Max = 100001;Â
    static int[] spf = new int[Max];Â
    // Function to precalculate smallest    // prime factor of every number    public static void sieve()    {        // Marking smallest prime factor        // of every number to itself        for (int i = 1; i < Max; i++)            spf[i] = i;Â
        // Marking smallest prime factor        // of every even number to be 2        for (int i = 4; i < Max; i = i + 2)            spf[i] = 2;Â
        for (int i = 3; i * i < Max; i++)Â
            // checking if i is prime            if (spf[i] == i) {Â
                // Marking spf for all                // numbers divisible by i                for (int j = i * i; j < Max; j = j + i) {Â
                    // Marking spf[j] if it is not                    // previously marked                    if (spf[j] == j)                        spf[j] = i;                }            }    }Â
    // Function to find maximum    // distinct prime factors    // of the subarray of length k    public static int maximumDPF(int[] arr,                                 int n, int k)    {        // precalculating Smallest Prime Factor        sieve();Â
        int ans = 0, num, currentCount;Â
        // Stores distinct prime factors        // for subarrays of size k        var maps = new Dictionary<int, int>();Â
        // Calculating the total prime factors        // for first k array elements        for (int i = 0; i < k; i++) {Â
            // Calculating prime factors of            // every element in O(logn)            num = arr[i];            while (num != 1) {Â
                // Increase frequencies of                // prime factors                maps.TryGetValue(spf[num],                                 out currentCount);                maps[spf[num]] = currentCount + 1;                num = num / spf[num];            }        }Â
        // Update maximum distinct        // prime factors obtained        ans = Math.Max(maps.Count, ans);Â
        for (int i = k; i < n; i++) {Â
            // Remove prime factors of            // removed element            num = arr[i - k];            while (num != 1) {Â
                // Reduce frequencies                // of prime factors                maps.TryGetValue(spf[num],                                 out currentCount);                maps[spf[num]] = currentCount - 1;Â
                if (maps[spf[num]] == 0)Â
                    // Erase that index from map                    maps.Remove(spf[num]);Â
                num = num / spf[num];            }Â
            // Insert prime factors            // added element            num = arr[i];            while (num != 1) {Â
                // Increase frequencies                // of prime factors                maps.TryGetValue(spf[num],                                 out currentCount);                maps[spf[num]] = currentCount + 1;                num = num / spf[num];            }Â
            ans = Math.Max(maps.Count, ans);        }Â
        // Update maximum distinct        // prime factors obtained        return ans;    }Â
    // Driver code    static public void Main()    {Â
        // Given array arr[]        int[] arr = { 4, 2, 6, 10 };Â
        // Given subarray size K        int k = 3;        int n = arr.Length;Â
        Console.Write(maximumDPF(arr, n, k));    }} |
Javascript
<script>    // JavaScript program for the above approach         const Max = 100001Â
    // Stores smallest prime    // factor for every number    let spf = new Array(Max).fill(0);Â
    // Function to calculate smallest    // prime factor of every number    const sieve = () => {             // Marking smallest prime factor        // of every number to itself        for (let i = 1; i < Max; i++)            spf[i] = i;Â
        // Separately marking smallest prime        // factor of every even number to be 2        for (let i = 4; i < Max; i = i + 2)            spf[i] = 2;Â
        for (let i = 3; i * i < Max; i++)Â
            // If i is prime            if (spf[i] == i) {Â
                // Mark spf for all numbers divisible by i                for (let j = i * i; j < Max; j = j + i) {Â
                    // Marking spf[j] if it is not                    // previously marked                    if (spf[j] == j)                        spf[j] = i;                }            }    }Â
    // Function to find maximum distinct    // prime factors of subarray of length k    const maximumDPF = (arr, n, k) => {        // Precalculate Smallest        // Prime Factors        sieve();Â
        let ans = 0, num;Â
        // Stores distinct prime factors        // for subarrays of size k        let maps = {};Â
        // Calculate total prime factors        // for first k array elements        for (let i = 0; i < k; i++) {Â
            // Calculate prime factors of            // every element in O(logn)            num = arr[i];            while (num != 1) {Â
                maps[spf[num]]++;                num = parseInt(num / spf[num]);            }        }Â
        // Update maximum distinct        // prime factors obtained        ans = Math.max(Object.keys(maps).length, ans);Â
        for (let i = k; i < n; i++) {Â
            // Remove prime factors of            // the removed element            num = arr[i - k];            while (num != 1) {Â
                // Reduce frequencies                // of prime factors                if (spf[num] in maps) maps[spf[num]]--;Â
                if (maps[spf[num]] == 0)Â
                    // Erase that index from map                    delete maps[spf[num]];Â
                num = parseInt(num / spf[num]);            }Â
            // Find prime factoes of            // added element            num = arr[i];            while (num != 1) {Â
                // Increase frequencies                // of prime factors                maps[spf[num]] = spf[num] in maps ? maps[spf[num]] + 1 : 1;                num = parseInt(num / spf[num]);            }Â
            // Update maximum distinct            // prime factors obtained            ans = Math.max(Object.keys(maps).length, ans);        }Â
        return ans;    }Â
    // Driver CodeÂ
    let arr = [4, 2, 6, 10];    let k = 3;    let n = arr.length;Â
    document.write(maximumDPF(arr, n, k));Â
// This code is contributed by rakeshsahniÂ
</script> |
3
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



