Open In App

Find the array element having equal count of Prime Numbers on its left and right

Given an array arr[] consisting of N positive integers, the task is to find an index from the array having count of prime numbers present on its left and right are equal.

Examples:



Input: arr[] = {2, 3, 4, 7, 5, 10, 1, 8}
Output: 2
Explanation: 
Consider the index 2, then the prime numbers to its left are {2, 3} and the prime numbers to its right are {7, 5}.
As, the count of prime numbers to the left and right index is 2, which is equal. Therefore, print 2.

Input: arr[] = {8, 10, 2, 7, 3}
Output: 3



Naive Approach: The simplest approach to solve the given problem is to count the prime numbers to the left and right of each array element by traversing the array and print the index at which the count of prime numbers are found to be equal. 
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized using the Sieve of Eratosthenes and prefix sum technique to pre-store the prime numbers left and right to an array element. Follow the steps below to solve the problem:

Below is the implementation of the above approach:




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the index of the
// array such that the count of prime
// numbers to its either ends are same
int findIndex(int arr[], int N)
{
    // Store the maximum value in
    // the array
    int maxValue = INT_MIN;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        maxValue = max(maxValue, arr[i]);
    }
 
    // Stores all the numbers
    map<int, int> St;
 
    // Iterate over the range [1, Max]
    for (int i = 1; i <= maxValue; i++) {
 
        // Increment the value of st[i]
        St[i]++;
    }
 
    // Removes 1 from the map St
    if (St.find(1) != St.end()) {
        St.erase(1);
    }
 
    // Perform Sieve of Prime Numbers
    for (int i = 2;
         i <= sqrt(maxValue); i++) {
        int j = 2;
 
        // While i*j is less than
        // the maxValue
        while ((i * j) <= maxValue) {
 
            // If i*j is in map St
            if (St.find(i * j)
                != St.end()) {
 
                // Erase the value (i * j)
                St.erase(i * j);
            }
 
            // Increment the value of j
            j++;
        }
    }
 
    // Stores the count of prime from
    // index 0 to i
    int LeftCount = 0;
 
    // Stores the count of prime numbers
    int Prefix[N];
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        Prefix[i] = LeftCount;
 
        // If arr[i] is present in the
        // map st
        if (St.find(arr[i])
            != St.end()) {
            LeftCount++;
        }
    }
 
    // Stores the count of prime from
    // index i to N-1
    int RightCount = 0;
 
    // Stores the count of prime numbers
    int Suffix[N];
 
    // Iterate over the range [0, N-1]
    // in reverse order
    for (int i = N - 1; i >= 0; i--) {
 
        Suffix[i] = RightCount;
 
        // If arr[i] is in map st
        if (St.find(arr[i])
            != St.end()) {
            RightCount++;
        }
    }
 
    // Iterate over the range [0, N-1]
    for (int i = 0; i < N; i++) {
 
        // If prefix[i] is equal
        // to the Suffix[i]
        if (Prefix[i] == Suffix[i]) {
            return i;
        }
    }
 
    // Return -1 if no such index
    // is present
    return -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 7, 5, 10, 1, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findIndex(arr, N);
 
    return 0;
}




// Java program for the above approach
import java.util.HashMap;
 
public class GFG
{
   
    // Function to find the index of the
    // array such that the count of prime
    // numbers to its either ends are same
    static int findIndex(int arr[], int N)
    {
       
        // Store the maximum value in
        // the array
        int maxValue = Integer.MIN_VALUE;
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++)
        {
            maxValue = Math.max(maxValue, arr[i]);
        }
 
        // Stores all the numbers
        HashMap<Integer, Integer> St = new HashMap<>();
 
        // Iterate over the range [1, Max]
        for (int i = 1; i <= maxValue; i++) {
 
            // Increment the value of st[i]
            St.put(i, St.getOrDefault(i, 0) + 1);
        }
 
        // Removes 1 from the map St
        if (St.containsKey(1)) {
            St.remove(1);
        }
 
        // Perform Sieve of Prime Numbers
        for (int i = 2; i <= Math.sqrt(maxValue); i++) {
            int j = 2;
 
            // While i*j is less than
            // the maxValue
            while ((i * j) <= maxValue) {
 
                // If i*j is in map St
                if (St.containsKey(i * j)) {
 
                    // Erase the value (i * j)
                    St.remove(i * j);
                }
 
                // Increment the value of j
                j++;
            }
        }
 
        // Stores the count of prime from
        // index 0 to i
        int LeftCount = 0;
 
        // Stores the count of prime numbers
        int Prefix[] = new int[N];
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
 
            Prefix[i] = LeftCount;
 
            // If arr[i] is present in the
            // map st
            if (St.containsKey(arr[i])) {
                LeftCount++;
            }
        }
 
        // Stores the count of prime from
        // index i to N-1
        int RightCount = 0;
 
        // Stores the count of prime numbers
        int Suffix[] = new int[N];
 
        // Iterate over the range [0, N-1]
        // in reverse order
        for (int i = N - 1; i >= 0; i--) {
 
            Suffix[i] = RightCount;
 
            // If arr[i] is in map st
            if (St.containsKey(arr[i])) {
                RightCount++;
            }
        }
 
        // Iterate over the range [0, N-1]
        for (int i = 0; i < N; i++) {
 
            // If prefix[i] is equal
            // to the Suffix[i]
            if (Prefix[i] == Suffix[i]) {
                return i;
            }
        }
 
        // Return -1 if no such index
        // is present
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 3, 4, 7, 5, 10, 1, 8 };
        int N = arr.length;
        System.out.println(findIndex(arr, N));
    }
}
 
// This code is contributed by abhinavjain194




# Python 3 program for the above approach
from collections import defaultdict
import sys
import math
 
# Function to find the index of the
# array such that the count of prime
# numbers to its either ends are same
 
 
def findIndex(arr, N):
 
    # Store the maximum value in
    # the array
    maxValue = -sys.maxsize - 1
 
    # Traverse the array arr[]
    for i in range(N):
        maxValue = max(maxValue, arr[i])
 
    # / Stores all the numbers
    St = defaultdict(int)
 
    # Iterate over the range [1, Max]
    for i in range(1, maxValue + 1):
 
        # Increment the value of st[i]
        St[i] += 1
 
    # Removes 1 from the map St
    if (1 in St):
        St.pop(1)
 
    # Perform Sieve of Prime Numbers
    for i in range(2, int(math.sqrt(maxValue)) + 1):
        j = 2
 
        # While i*j is less than
        # the maxValue
        while ((i * j) <= maxValue):
 
            # If i*j is in map St
            if (i * j) in St:
 
                # Erase the value (i * j)
                St.pop(i * j)
 
            # Increment the value of j
            j += 1
 
    # Stores the count of prime from
    # index 0 to i
    LeftCount = 0
 
    # Stores the count of prime numbers
    Prefix = [0] * N
 
    # Traverse the array arr[]
    for i in range(N):
 
        Prefix[i] = LeftCount
 
        # If arr[i] is present in the
        # map st
        if (arr[i] in St):
            LeftCount += 1
 
    # Stores the count of prime from
    # index i to N-1
    RightCount = 0
 
    # Stores the count of prime numbers
    Suffix = [0] * N
 
    # Iterate over the range [0, N-1]
    # in reverse order
    for i in range(N - 1, -1, -1):
 
        Suffix[i] = RightCount
 
        # If arr[i] is in map st
        if arr[i] in St:
            RightCount += 1
 
    # Iterate over the range [0, N-1]
    for i in range(N):
 
        # If prefix[i] is equal
        # to the Suffix[i]
        if (Prefix[i] == Suffix[i]):
            return i
 
    # Return -1 if no such index
    # is present
    return -1
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [2, 3, 4, 7, 5, 10, 1, 8]
    N = len(arr)
    print(findIndex(arr, N))
 
    # This code is contributed by ukasp.




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
      // Function to find the index of the
    // array such that the count of prime
    // numbers to its either ends are same
    static int findIndex(int[] arr, int N)
    {
       
        // Store the maximum value in
        // the array
        int maxValue = Int32.MinValue;
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++)
        {
            maxValue = Math.Max(maxValue, arr[i]);
        }
 
        // Stores all the numbers
        Dictionary<int,int> St = new Dictionary<int,int>();
 
        // Iterate over the range [1, Max]
        for (int i = 1; i <= maxValue; i++) {
 
            // Increment the value of st[i]
            St.Add(i, 1);
        }
 
        // Removes 1 from the map St
        if (St.ContainsKey(1)) {
            St.Remove(1);
        }
 
        // Perform Sieve of Prime Numbers
        for (int i = 2; i <= Math.Sqrt(maxValue); i++) {
            int j = 2;
 
            // While i*j is less than
            // the maxValue
            while ((i * j) <= maxValue) {
 
                // If i*j is in map St
                if (St.ContainsKey(i * j)) {
 
                    // Erase the value (i * j)
                    St.Remove(i * j);
                }
 
                // Increment the value of j
                j++;
            }
        }
 
        // Stores the count of prime from
        // index 0 to i
        int LeftCount = 0;
 
        // Stores the count of prime numbers
        int[] Prefix = new int[N];
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
 
            Prefix[i] = LeftCount;
 
            // If arr[i] is present in the
            // map st
            if (St.ContainsKey(arr[i])) {
                LeftCount++;
            }
        }
 
        // Stores the count of prime from
        // index i to N-1
        int RightCount = 0;
 
        // Stores the count of prime numbers
        int[] Suffix = new int[N];
 
        // Iterate over the range [0, N-1]
        // in reverse order
        for (int i = N - 1; i >= 0; i--) {
 
            Suffix[i] = RightCount;
 
            // If arr[i] is in map st
            if (St.ContainsKey(arr[i])) {
                RightCount++;
            }
        }
 
        // Iterate over the range [0, N-1]
        for (int i = 0; i < N; i++) {
 
            // If prefix[i] is equal
            // to the Suffix[i]
            if (Prefix[i] == Suffix[i]) {
                return i;
            }
        }
 
        // Return -1 if no such index
        // is present
        return -1;
    }
 
    // Driver code
    static public void Main (){
 
        int[] arr = { 2, 3, 4, 7, 5, 10, 1, 8 };
        int N = arr.Length;
        Console.WriteLine(findIndex(arr, N));
    }
}
 
// This code is contributed by Dharanendra L V.




<script>
 
// JavaScript program to count frequencies of array items
 
// Function to find the index of the
// array such that the count of prime
// numbers to its either ends are same
function findIndex( arr,  N)
    {
     
        // Store the maximum value in
        // the array
        let maxValue = Number.MIN_VALUE;
;
 
        // Traverse the array arr[]
        for (let i = 0; i < N; i++)
        {
            maxValue = Math.max(maxValue, arr[i]);
        }
 
        // Stores all the numbers
        var St = new Map();
 
        // Iterate over the range [1, Max]
        for (let i = 1; i <= maxValue; i++) {
 
            // Increment the value of st[i]
            St.set(i, 1);
        }
 
        // Removes 1 from the map St
        if (St.has(1)) {
            St.delete(1);
        }
 
        // Perform Sieve of Prime Numbers
        for (let i = 2; i <= Math.sqrt(maxValue); i++) {
            let j = 2;
 
            // While i*j is less than
            // the maxValue
            while ((i * j) <= maxValue) {
 
                // If i*j is in map St
                if (St.has(i * j)) {
 
                    // Erase the value (i * j)
                    St.delete(i * j);
                }
 
                // Increment the value of j
                j++;
            }
        }
 
        // Stores the count of prime from
        // index 0 to i
        let LeftCount = 0;
 
        // Stores the count of prime numbers
        let Prefix = new Array(N);
 
        // Traverse the array arr[]
        for (let i = 0; i < N; i++) {
 
            Prefix[i] = LeftCount;
 
            // If arr[i] is present in the
            // map st
            if (St.has(arr[i])) {
                LeftCount++;
            }
        }
 
        // Stores the count of prime from
        // index i to N-1
        let RightCount = 0;
 
        // Stores the count of prime numbers
        let Suffix = new Array(N);
 
        // Iterate over the range [0, N-1]
        // in reverse order
        for (let i = N - 1; i >= 0; i--) {
 
            Suffix[i] = RightCount;
 
            // If arr[i] is in map st
            if (St.has(arr[i])) {
                RightCount++;
            }
        }
 
        // Iterate over the range [0, N-1]
        for (let i = 0; i < N; i++) {
 
            // If prefix[i] is equal
            // to the Suffix[i]
            if (Prefix[i] == Suffix[i]) {
                return i;
            }
        }
 
        // Return -1 if no such index
        // is present
        return -1;
    }
 
// Driver Code
let arr = [ 2, 3, 4, 7, 5, 10, 1, 8 ];
let N = arr.length;
document.write(findIndex(arr, N));
 
// This code is contributed by jana_sayantan.
</script>

Output: 
2

 

Time Complexity: O(N * log N)
Auxiliary Space: O(N)


Article Tags :