![]() |
VOOZH | about |
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 = 18Input: 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:
Below is the implementation of the above approach:
3
Time Complexity: O(N + max(arr[])loglog(max(arr[]))
Auxiliary Space: O(max(arr[]) + N)