VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-array-element-having-equal-sum-of-prime-numbers-on-its-left-and-right/

⇱ Find the array element having equal sum of Prime Numbers on its left and right - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


Output: 
3

 

Time Complexity: O(N + max(arr[])loglog(max(arr[]))
Auxiliary Space: O(max(arr[]) + N)

Comment