Find the array element having equal sum of Prime Numbers on its left and right
Last Updated :
23 Jul, 2025
Given an array arr[] of size N, the task is to find the index in the given array where the sum of the prime numbers present to its left is equal to the sum of the prime numbers present to its right.
Examples:
Input: arr[] = {11, 4, 7, 6, 13, 1, 5}
Output: 3
Explanation: Sum of prime numbers to left of index 3 = 11 + 7 = 18
Sum of prime numbers to right of index 3 = 13 + 5 = 18
Input: arr[] = {5, 2, 1, 7}
Output: 2
Explanation: Sum of prime numbers to left of index 2 = 5 + 2 = 7
Sum of prime numbers to right of index 2 = 7
Naive Approach: The simplest approach is to traverse the array and check for the given condition for every index in the range [0, N - 1]. If the condition is found to be true for any index, then print the value of that index.
Time Complexity: O(N2*?M), where M is the largest element in the array
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 sum of prime numbers left and right to an array element. Follow the steps below to solve the problem:
- Traverse through the array to find the maximum value present in the array.
- Use Sieve of Eratosthenes to find out the prime numbers which are less than or equal to the maximum value present in the array. Store these elements in a Map.
- Initialize an array, say first_array. Traverse the array and store the sum of all prime numbers up to ith index at first_array[i].
- Initialize an array, say second_array. Traverse the array in reverse and store the sum of all elements up to ith index at second_array[i].
- Traverse the arrays first_array and second_array and check if at any index, both their values are equal or not. If found to be true, return that index.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
int find_index(int arr[], int N)
{
// Stores the maximum value
// present in the array
int max_value = INT_MIN;
for (int i = 0; i < N; i++) {
max_value = max(max_value, arr[i]);
}
// Stores all positive
// elements which are <= max_value
map<int, int> store;
for (int i = 1; i <= max_value; i++) {
store[i]++;
}
// If 1 is present
if (store.find(1) != store.end()) {
// Remove 1
store.erase(1);
}
// Sieve of Eratosthenes to
// store all prime numbers which
// are <= max_value in the Map
for (int i = 2; i <= sqrt(max_value); i++) {
int multiple = 2;
// Erase non-prime numbers
while ((i * multiple) <= max_value) {
if (store.find(i * multiple) != store.end()) {
store.erase(i * multiple);
}
multiple++;
}
}
// Stores the sum of
// prime numbers from left
int prime_sum_from_left = 0;
// Stores the sum of prime numbers
// to the left of each index
int first_array[N];
for (int i = 0; i < N; i++) {
// Stores the sum of prime numbers
// to the left of the current index
first_array[i] = prime_sum_from_left;
if (store.find(arr[i]) != store.end()) {
// Add current value to
// the prime sum if the
// current value is prime
prime_sum_from_left += arr[i];
}
}
// Stores the sum of
// prime numbers from right
int prime_sum_from_right = 0;
// Stores the sum of prime numbers
// to the right of each index
int second_array[N];
for (int i = N - 1; i >= 0; i--) {
// Stores the sum of prime
// numbers to the right of
// the current index
second_array[i] = prime_sum_from_right;
if (store.find(arr[i]) != store.end()) {
// Add current value to the
// prime sum if the
// current value is prime
prime_sum_from_right += arr[i];
}
}
// Traverse through the two
// arrays to find the index
for (int i = 0; i < N; i++) {
// Compare the values present
// at the current index
if (first_array[i] == second_array[i]) {
// Return the index where
// both the values are same
return i;
}
}
// No index is found.
return -1;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 11, 4, 7, 6, 13, 1, 5 };
// Size of Array
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
cout << find_index(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.lang.*;
import java.util.*;
class GFG{
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
static int find_index(int arr[], int N)
{
// Stores the maximum value
// present in the array
int max_value = Integer.MIN_VALUE;
for(int i = 0; i < N; i++)
{
max_value = Math.max(max_value, arr[i]);
}
// Stores all positive
// elements which are <= max_value
Map<Integer, Integer> store= new HashMap<>();
for(int i = 1; i <= max_value; i++)
{
store.put(i, store.getOrDefault(i, 0) + 1);
}
// If 1 is present
if (store.containsKey(1))
{
// Remove 1
store.remove(1);
}
// Sieve of Eratosthenes to
// store all prime numbers which
// are <= max_value in the Map
for(int i = 2; i <= Math.sqrt(max_value); i++)
{
int multiple = 2;
// Erase non-prime numbers
while ((i * multiple) <= max_value)
{
if (store.containsKey(i * multiple))
{
store.remove(i * multiple);
}
multiple++;
}
}
// Stores the sum of
// prime numbers from left
int prime_sum_from_left = 0;
// Stores the sum of prime numbers
// to the left of each index
int[] first_array = new int[N];
for(int i = 0; i < N; i++)
{
// Stores the sum of prime numbers
// to the left of the current index
first_array[i] = prime_sum_from_left;
if (store.containsKey(arr[i]))
{
// Add current value to
// the prime sum if the
// current value is prime
prime_sum_from_left += arr[i];
}
}
// Stores the sum of
// prime numbers from right
int prime_sum_from_right = 0;
// Stores the sum of prime numbers
// to the right of each index
int[] second_array= new int[N];
for(int i = N - 1; i >= 0; i--)
{
// Stores the sum of prime
// numbers to the right of
// the current index
second_array[i] = prime_sum_from_right;
if (store.containsKey(arr[i]))
{
// Add current value to the
// prime sum if the
// current value is prime
prime_sum_from_right += arr[i];
}
}
// Traverse through the two
// arrays to find the index
for(int i = 0; i < N; i++)
{
// Compare the values present
// at the current index
if (first_array[i] == second_array[i])
{
// Return the index where
// both the values are same
return i;
}
}
// No index is found.
return -1;
}
// Driver code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 11, 4, 7, 6, 13, 1, 5 };
// Size of Array
int N = arr.length;
// Function Call
System.out.println(find_index(arr, N));
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
from math import sqrt
# Function to find an index in the
# array having sum of prime numbers
# to its left and right equal
def find_index(arr, N):
# Stores the maximum value
# present in the array
max_value = -10**9
for i in range(N):
max_value = max(max_value, arr[i])
# Stores all positive
# elements which are <= max_value
store = {}
for i in range(1, max_value + 1):
store[i] = store.get(i, 0) + 1
# If 1 is present
if (1 in store):
# Remove 1
del store[1]
# Sieve of Eratosthenes to
# store all prime numbers which
# are <= max_value in the Map
for i in range(2, int(sqrt(max_value)) + 1):
multiple = 2
# Erase non-prime numbers
while ((i * multiple) <= max_value):
if (i * multiple in store):
del store[i * multiple]
multiple += 1
# Stores the sum of
# prime numbers from left
prime_sum_from_left = 0
# Stores the sum of prime numbers
# to the left of each index
first_array = [0]*N
for i in range(N):
# Stores the sum of prime numbers
# to the left of the current index
first_array[i] = prime_sum_from_left
if arr[i] in store:
# Add current value to
# the prime sum if the
# current value is prime
prime_sum_from_left += arr[i]
# Stores the sum of
# prime numbers from right
prime_sum_from_right = 0
# Stores the sum of prime numbers
# to the right of each index
second_array = [0]*N
for i in range(N - 1, -1, -1):
# Stores the sum of prime
# numbers to the right of
# the current index
second_array[i] = prime_sum_from_right
if (arr[i] in store):
# Add current value to the
# prime sum if the
# current value is prime
prime_sum_from_right += arr[i]
# Traverse through the two
# arrays to find the index
for i in range(N):
# Compare the values present
# at the current index
if (first_array[i] == second_array[i]):
# Return the index where
# both the values are same
return i
# No index is found.
return -1
# Driver Code
if __name__ == '__main__':
# Given array arr[]
arr= [11, 4, 7, 6, 13, 1, 5]
# Size of Array
N = len(arr)
# Function Call
print (find_index(arr, N))
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
static int find_index(int[] arr, int N)
{
// Stores the maximum value
// present in the array
int max_value = Int32.MinValue;
for(int i = 0; i < N; i++)
{
max_value = Math.Max(max_value, arr[i]);
}
// Stores all positive
// elements which are <= max_value
Dictionary<int,
int> store = new Dictionary<int,
int>();
for(int i = 1; i <= max_value; i++)
{
if (!store.ContainsKey(i))
store[i] = 0;
store[i]++;
}
// If 1 is present
if (store.ContainsKey(1))
{
// Remove 1
store.Remove(1);
}
// Sieve of Eratosthenes to
// store all prime numbers which
// are <= max_value in the Map
for(int i = 2; i <= Math.Sqrt(max_value); i++)
{
int multiple = 2;
// Erase non-prime numbers
while ((i * multiple) <= max_value)
{
if (store.ContainsKey(i * multiple))
{
store.Remove(i * multiple);
}
multiple++;
}
}
// Stores the sum of
// prime numbers from left
int prime_sum_from_left = 0;
// Stores the sum of prime numbers
// to the left of each index
int[] first_array = new int[N];
for(int i = 0; i < N; i++)
{
// Stores the sum of prime numbers
// to the left of the current index
first_array[i] = prime_sum_from_left;
if (store.ContainsKey(arr[i]))
{
// Add current value to
// the prime sum if the
// current value is prime
prime_sum_from_left += arr[i];
}
}
// Stores the sum of
// prime numbers from right
int prime_sum_from_right = 0;
// Stores the sum of prime numbers
// to the right of each index
int[] second_array = new int[N];
for(int i = N - 1; i >= 0; i--)
{
// Stores the sum of prime
// numbers to the right of
// the current index
second_array[i] = prime_sum_from_right;
if (store.ContainsKey(arr[i]))
{
// Add current value to the
// prime sum if the
// current value is prime
prime_sum_from_right += arr[i];
}
}
// Traverse through the two
// arrays to find the index
for(int i = 0; i < N; i++)
{
// Compare the values present
// at the current index
if (first_array[i] == second_array[i])
{
// Return the index where
// both the values are same
return i;
}
}
// No index is found.
return -1;
}
// Driver Code
public static void Main()
{
// Given array arr[]
int[] arr = { 11, 4, 7, 6, 13, 1, 5 };
// Size of Array
int N = arr.Length;
// Function Call
Console.WriteLine(find_index(arr, N));
}
}
// This code is contributed by ukasp
JavaScript
<script>
// Javascript program for the above approach
// Function to find an index in the
// array having sum of prime numbers
// to its left and right equal
function find_index(arr,N)
{
// Stores the maximum value
// present in the array
let max_value = Number.MIN_VALUE;
for (let i = 0; i < N; i++) {
max_value = Math.max(max_value, arr[i]);
}
// Stores all positive
// elements which are <= max_value
let store=new Map();
for (let i = 1; i <= max_value; i++) {
if(!store.has(i))
store.set(i,0);
store.set(i,store.get(i)+1);
}
// If 1 is present
if (store.has(1)) {
// Remove 1
store.delete(1);
}
// Sieve of Eratosthenes to
// store all prime numbers which
// are <= max_value in the Map
for (let i = 2; i <= Math.sqrt(max_value); i++) {
let multiple = 2;
// Erase non-prime numbers
while ((i * multiple) <= max_value) {
if (store.has(i * multiple)) {
store.delete(i * multiple);
}
multiple++;
}
}
// Stores the sum of
// prime numbers from left
let prime_sum_from_left = 0;
// Stores the sum of prime numbers
// to the left of each index
let first_array=new Array(N);
for (let i = 0; i < N; i++) {
// Stores the sum of prime numbers
// to the left of the current index
first_array[i] = prime_sum_from_left;
if (store.has(arr[i])) {
// Add current value to
// the prime sum if the
// current value is prime
prime_sum_from_left += arr[i];
}
}
// Stores the sum of
// prime numbers from right
let prime_sum_from_right = 0;
// Stores the sum of prime numbers
// to the right of each index
let second_array=new Array(N);
for (let i = N - 1; i >= 0; i--) {
// Stores the sum of prime
// numbers to the right of
// the current index
second_array[i] = prime_sum_from_right;
if (store.has(arr[i]) ) {
// Add current value to the
// prime sum if the
// current value is prime
prime_sum_from_right += arr[i];
}
}
// Traverse through the two
// arrays to find the index
for (let i = 0; i < N; i++) {
// Compare the values present
// at the current index
if (first_array[i] == second_array[i]) {
// Return the index where
// both the values are same
return i;
}
}
// No index is found.
return -1;
}
// Driver Code
// Given array arr[]
let arr=[11, 4, 7, 6, 13, 1, 5];
// Size of Array
let N=arr.length;
// Function Call
document.write(find_index(arr, N));
// This code is contributed by patel2127
</script>
Time Complexity: O(N + max(arr[])loglog(max(arr[]))
Auxiliary Space: O(max(arr[]) + N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem