Open In App

Find the index having sum of elements on its left equal to reverse of the sum of elements on its right

Last Updated : 20 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, arr[] size N, the task is to find the smallest index of the array such that the sum of all the array elements on the left side of the index is equal to the reverse of the digits of the sum of all the array elements on the right side of that index. If no such index is found then print -1.

Examples:

Input: arr[] = { 5, 7, 3, 6, 4, 9, 2 } 
Output:
Explanation: 
Sum of array elements on left side of index 2 = (5 + 7) = 12 
Sum of array elements on right side of index 2 = (6 + 4 + 9 + 2) = 21 
Since sum of array elements on left side of index 2 equal to the reverse of the digits of sum of elements on the right side of index 2. Therefore, the required output is 2.

Input: arr[] = { 1, 3, 6, 8, 9, 2 } 
Output: -1

Naive Approach: The simplest approach to solve this problem is to traverse the array and for each index, check if the sum of elements on the left side of the index is equal to the reverse of the digits of the sum of the array elements on the right side of that index or not. If found to be true, then print that index. Otherwise, if no such index is found, print -1.

  1. Iterate through the vector using a for loop with an index i from 0 to n-1.
  2. Inside the for loop, call the function sum_left passing in the vector, n and the current index i, which returns
    the sum of all elements in the vector before the current index.
  3. Call the function sum_right passing in the vector, n, and the current index i, which returns the sum of all elements in the vector after the current index.
  4. Convert the result from step 3 to a string and store in variable sum_r_str
  5. Reverse the string from step 4 and store it in variable sum_r_str_reversed
  6. Compare sum_l from step 2 with the result of the string from step 5, stoi(sum_r_str_reversed)
  7. If the comparison is true, print i and return 0, otherwise continue with the for loop.
  8. If for loop is finished, print -1 and return 0

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int sum_left(vector<int>& arr, int n, int index)
{
    int sum = 0;
    for (int i = 0; i < index; i++) {
        sum += arr[i];
    }
    return sum;
}
 
int sum_right(vector<int>& arr, int n, int index)
{
    int sum = 0;
    for (int i = index + 1; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}
 
string reverse_string(string str)
{
    reverse(str.begin(), str.end());
    return str;
}
 
int main()
{
    vector<int> arr = { 5, 7, 3, 6, 4, 9, 2 };
    int n = arr.size();
 
    for (int i = 0; i < n; i++) {
        int sum_l = sum_left(arr, n, i);
        int sum_r = sum_right(arr, n, i);
        string sum_r_str = to_string(sum_r);
        string sum_r_str_reversed
            = reverse_string(sum_r_str);
        if (sum_l == stoi(sum_r_str_reversed)) {
            cout << i << endl;
            return 0;
        }
    }
    cout << -1 << endl;
    return 0;
}


Java




import java.util.Arrays;
import java.util.Vector;
 
public class Gfg {
    public static int sum_left(Vector<Integer> arr, int n,
                               int index)
    {
        int sum = 0;
        for (int i = 0; i < index; i++) {
            sum += arr.get(i);
        }
        return sum;
    }
 
    public static int sum_right(Vector<Integer> arr, int n,
                                int index)
    {
        int sum = 0;
        for (int i = index + 1; i < n; i++) {
            sum += arr.get(i);
        }
        return sum;
    }
 
    public static String reverse_string(String str)
    {
        StringBuilder sb = new StringBuilder(str);
        return sb.reverse().toString();
    }
 
    public static void main(String[] args)
    {
        Vector<Integer> arr = new Vector<Integer>(
            Arrays.asList(5, 7, 3, 6, 4, 9, 2));
        int n = arr.size();
 
        for (int i = 0; i < n; i++) {
            int sum_l = sum_left(arr, n, i);
            int sum_r = sum_right(arr, n, i);
            String sum_r_str = Integer.toString(sum_r);
            String sum_r_str_reversed
                = reverse_string(sum_r_str);
            if (sum_l
                == Integer.parseInt(sum_r_str_reversed)) {
                System.out.println(i);
                return;
            }
        }
        System.out.println(-1);
    }
}
 
// This code is contributed by divya_p123.


Python3




def sum_left(arr, n, index):
    sum = 0;
    for i in range(0,index):
        sum += arr[i];
    return sum;
 
def sum_right( arr, n, index):
    sum = 0;
    for i in range(index+1,n):
        sum += arr[i];
     
    return sum;
 
def reverse_string( string):
    return string[::-1]
 
arr = [ 5, 7, 3, 6, 4, 9, 2 ];
n = len(arr);
 
for i in range(0,n):
    sum_l = sum_left(arr, n, i);
    sum_r = sum_right(arr, n, i);
    sum_r_str = str(sum_r);
    f=0;
    sum_r_str_reverse = reverse_string(sum_r_str);
    if (sum_l == int(sum_r_str_reverse)):
        print(i);
        f=1;
        break;
if(f == 0):
    print(-1);
  
# This code was contributed by poojaagrawal2.


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
    static int SumLeft(List<int> arr, int n, int index)
    {
        int sum = 0;
        for (int i = 0; i < index; i++) {
            sum += arr[i];
        }
        return sum;
    }
 
    static int SumRight(List<int> arr, int n, int index)
    {
        int sum = 0;
        for (int i = index + 1; i < n; i++) {
            sum += arr[i];
        }
        return sum;
    }
 
    static string ReverseString(string str)
    {
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
 
    static public void Main(string[] args)
    {
        List<int> arr
            = new List<int>{ 5, 7, 3, 6, 4, 9, 2 };
        int n = arr.Count();
 
        for (int i = 0; i < n; i++) {
            int sumLeft = SumLeft(arr, n, i);
            int sumRight = SumRight(arr, n, i);
            string sumRightStr = sumRight.ToString();
            string sumRightStrReversed
                = ReverseString(sumRightStr);
            if (sumLeft == int.Parse(sumRightStrReversed)) {
                Console.WriteLine(i);
                return;
            }
        }
        Console.WriteLine(-1);
    }
}
 
// This code is contributed by Prasad Kandekar(prasad264)


Javascript




function sum_left(arr, n, index) {
    let sum = 0;
    for (let i = 0; i < index; i++) {
        sum += arr[i];
    }
    return sum;
}
 
function sum_right(arr, n, index) {
    let sum = 0;
    for (let i = index + 1; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}
 
function reverse_string(str) {
    return str.split('').reverse().join('');
}
let arr = [5, 7, 3, 6, 4, 9, 2];
let n = arr.length;
 
for (let i = 0; i < n; i++) {
    let sum_l = sum_left(arr, n, i);
    let sum_r = sum_right(arr, n, i);
    let sum_r_str = sum_r.toString();
    let sum_r_str_reversed = reverse_string(sum_r_str);
    if (sum_l === parseInt(sum_r_str_reversed)) {
        console.log(i);
        return;
    }
}
console.log(-1);
 
// This code is contributed by agrawalpoojaa976.


Output

2





Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach the idea is to use prefix-sum technique. Follow the steps below to solve the problem:

  • Initialize a variable, say rightSum, to store the sum of the array elements on the right side of each index.
  • Initialize a variable, say leftSum, to store the sum of array elements on the left side of each index.
  • Traverse the array using variable i and update the value of rightSum -= arr[i], leftSum += arr[i] and check if leftSum equal to the reverse of digits of rightSum or not. If found to be true then print i.
  • Otherwise, print -1.

Below is the implementation of the above approach.

C++




// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a number is equal
// to the reverse of digits of other number
bool checkReverse(int leftSum, int rightSum)
{
    // Stores reverse of
    // digits of rightSum
    int rev = 0;
 
    // Stores rightSum
    int temp = rightSum;
 
    // Calculate reverse of
    // digits of temp
    while (temp != 0) {
 
        // Update rev
        rev = (rev * 10) + (temp % 10);
 
        // Update temp
        temp /= 10;
    }
 
    // If reverse of digits of
    // rightSum equal to leftSum
    if (rev == leftSum) {
        return true;
    }
 
    return false;
}
 
// Function to find the index
// that satisfies the condition
int findIndex(int arr[], int N)
{
 
    // Stores sum of array elements
    // on right side of each index
    int rightSum = 0;
 
    // Stores sum of array elements
    // on left side of each index
    int leftSum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update rightSum
        rightSum += arr[i];
    }
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update rightSum
        rightSum -= arr[i];
 
        // If leftSum equal to
        // reverse of digits
        // of rightSum
        if (checkReverse(leftSum,
                         rightSum)) {
            return i;
        }
 
        // Update leftSum
        leftSum += arr[i];
    }
 
    return -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 7, 3, 6, 4, 9, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findIndex(arr, N);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
class GFG {
 
  // Function to check if a number is equal
  // to the reverse of digits of other number
  static boolean checkReverse(int leftSum, int rightSum)
  {
    // Stores reverse of
    // digits of rightSum
    int rev = 0;
 
    // Stores rightSum
    int temp = rightSum;
 
    // Calculate reverse of
    // digits of temp
    while (temp != 0) {
 
      // Update rev
      rev = (rev * 10) + (temp % 10);
 
      // Update temp
      temp /= 10;
    }
 
    // If reverse of digits of
    // rightSum equal to leftSum
    if (rev == leftSum) {
      return true;
    }
 
    return false;
  }
 
  // Function to find the index
  // that satisfies the condition
  static int findIndex(int[] arr, int N)
  {
 
    // Stores sum of array elements
    // on right side of each index
    int rightSum = 0;
 
    // Stores sum of array elements
    // on left side of each index
    int leftSum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
      // Update rightSum
      rightSum += arr[i];
    }
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
      // Update rightSum
      rightSum -= arr[i];
 
      // If leftSum equal to
      // reverse of digits
      // of rightSum
      if (checkReverse(leftSum,
                       rightSum)) {
        return i;
      }
 
      // Update leftSum
      leftSum += arr[i];
    }
 
    return -1;
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    int[] arr = { 5, 7, 3, 6, 4, 9, 2 };
    int N = arr.length;
    System.out.print(findIndex(arr, N));
  }
}
 
// This code is contributed by code_hunt.


Python3




# Python3 Program to implement
# the above approach
 
# Function to check if a number is equal
# to the reverse of digits of other number
def checkReverse(leftSum, rightSum):
     
    # Stores reverse of
    # digits of rightSum
    rev = 0
 
    # Stores rightSum
    temp = rightSum
 
    # Calculate reverse of
    # digits of temp
    while (temp != 0):
 
        # Update rev
        rev = (rev * 10) + (temp % 10)
 
        # Update temp
        temp //= 10
 
    # If reverse of digits of
    # rightSum equal to leftSum
    if (rev == leftSum):
        return True
 
    return False
 
# Function to find the index
# that satisfies the condition
def findIndex(arr, N):
 
    # Stores sum of array elements
    # on right side of each index
    rightSum = 0
 
    # Stores sum of array elements
    # on left side of each index
    leftSum = 0
 
    # Traverse the array
    for i in range(N):
        
        # Update rightSum
        rightSum += arr[i]
 
    # Traverse the array
    for i in range(N):
 
        # Update rightSum
        rightSum -= arr[i]
 
        # If leftSum equal to
        # reverse of digits
        # of rightSum
        if (checkReverse(leftSum, rightSum)):
            return i
 
        # Update leftSum
        leftSum += arr[i]
    return -1
 
# Driver Code
if __name__ == '__main__':
    arr = [5, 7, 3, 6, 4, 9, 2]
    N =  len(arr)
    print(findIndex(arr, N))
 
    # This code is contributed by mohit kumar 29


C#




// C# Program to implement
// the above approach
using System;
class GFG {
     
    // Function to check if a number is equal
    // to the reverse of digits of other number
    static bool checkReverse(int leftSum, int rightSum)
    {
        // Stores reverse of
        // digits of rightSum
        int rev = 0;
      
        // Stores rightSum
        int temp = rightSum;
      
        // Calculate reverse of
        // digits of temp
        while (temp != 0) {
      
            // Update rev
            rev = (rev * 10) + (temp % 10);
      
            // Update temp
            temp /= 10;
        }
      
        // If reverse of digits of
        // rightSum equal to leftSum
        if (rev == leftSum) {
            return true;
        }
      
        return false;
    }
      
    // Function to find the index
    // that satisfies the condition
    static int findIndex(int[] arr, int N)
    {
      
        // Stores sum of array elements
        // on right side of each index
        int rightSum = 0;
      
        // Stores sum of array elements
        // on left side of each index
        int leftSum = 0;
      
        // Traverse the array
        for (int i = 0; i < N; i++) {
      
            // Update rightSum
            rightSum += arr[i];
        }
      
        // Traverse the array
        for (int i = 0; i < N; i++) {
      
            // Update rightSum
            rightSum -= arr[i];
      
            // If leftSum equal to
            // reverse of digits
            // of rightSum
            if (checkReverse(leftSum,
                             rightSum)) {
                return i;
            }
      
            // Update leftSum
            leftSum += arr[i];
        }
      
        return -1;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 5, 7, 3, 6, 4, 9, 2 };
    int N = arr.Length;
    Console.Write(findIndex(arr, N));
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript




<script>
 
// Javascript program for the above approach
 
    // Function to check if a number is equal
    // to the reverse of digits of other number
    function checkReverse(leftSum , rightSum) {
        // Stores reverse of
        // digits of rightSum
        var rev = 0;
 
        // Stores rightSum
        var temp = rightSum;
 
        // Calculate reverse of
        // digits of temp
        while (temp != 0) {
 
            // Update rev
            rev = (rev * 10) + (temp % 10);
 
            // Update temp
            temp = parseInt(temp/10);
        }
 
        // If reverse of digits of
        // rightSum equal to leftSum
        if (rev == leftSum) {
            return true;
        }
 
        return false;
    }
 
    // Function to find the index
    // that satisfies the condition
    function findIndex(arr , N) {
 
        // Stores sum of array elements
        // on right side of each index
        var rightSum = 0;
 
        // Stores sum of array elements
        // on left side of each index
        var leftSum = 0;
 
        // Traverse the array
        for (i = 0; i < N; i++) {
 
            // Update rightSum
            rightSum += arr[i];
        }
 
        // Traverse the array
        for (i = 0; i < N; i++) {
 
            // Update rightSum
            rightSum -= arr[i];
 
            // If leftSum equal to
            // reverse of digits
            // of rightSum
            if (checkReverse(leftSum, rightSum)) {
                return i;
            }
 
            // Update leftSum
            leftSum += arr[i];
        }
 
        return -1;
    }
 
    // Driver code
     
 
        var arr = [ 5, 7, 3, 6, 4, 9, 2 ];
        var N = arr.length;
        document.write(findIndex(arr, N));
 
// This code contributed by aashish1995
 
</script>


Output

2





Time Complexity: O(N) 
Auxiliary Space: O(1)

Approach 3: Binary Search :

Here’s the approach using binary search:

  • Initialize two vectors sum_left and sum_right to store the prefix sums of the array from the left and right respectively.
  • Traverse the array from left to right and calculate the prefix sums of the array from the left and store them in the vector sum_left.
  • Traverse the array from right to left and calculate the prefix sums of the array from the right and store them in the vector sum_right.
  • Initialize a variable n to be the size of the array.
  • For each index i in the array, do the following:
  • a. If the sum_left[i] equals the reversed string of sum_right[n-i-1], return i.
  • If no such index is found, return -1.
    Here’s the code:

C++




// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
 
// function to reverse the integer
int reverseInteger(int n) {
    int reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }
    return reversed;
}
 
// function to check the index
bool checkIndex(vector<int>& arr, int index) {
   
  // left sum variable
    int leftSum = 0;
    for (int i = 0; i < index; ++i) {
        leftSum += arr[i];
    }
     
  // right sum variable
    int rightSum = 0;
    for (int i = index + 1; i < arr.size(); ++i) {
        rightSum += arr[i];
    }
    // if left sum is equal to the reverse of the right sum then return true
    // else return false
    if (leftSum == reverseInteger(rightSum)) {
        return true;
    }
     
    return false;
}
 
// function to find the index
int findIndex(vector<int>& arr) {
   
  // total sum varaible
    int totalSum = 0;
    for (int num : arr) {
        totalSum += num;
    }
     
    int leftSum = 0;
    for (int i = 0; i < arr.size(); ++i) {
        int rightSum = totalSum - leftSum - arr[i];
       
       // if left sum is equal to the reverse of the right sum then return i
        if (leftSum == reverseInteger(rightSum)) {
            return i;
        }
        leftSum += arr[i];
    }
     
    return -1;
}
 
// driver code
int main() {
  vector<int> arr = {5, 7, 3, 6, 4, 9, 2};
    int index = findIndex(arr);
   
  // output
   cout << index << std::endl;
     
    return 0;
}


Java




public class Main {
 
    // Function to reverse an integer
    static int reverseInteger(int n) {
        int reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        return reversed;
    }
 
    // Function to check if an index satisfies the condition
    static boolean checkIndex(int[] arr, int index) {
        int leftSum = 0;
        for (int i = 0; i < index; ++i) {
            leftSum += arr[i];
        }
 
        int rightSum = 0;
        for (int i = index + 1; i < arr.length; ++i) {
            rightSum += arr[i];
        }
 
        return leftSum == reverseInteger(rightSum);
    }
 
    // Function to find the index
    static int findIndex(int[] arr) {
        int totalSum = 0;
        for (int i = 0; i < arr.length; ++i) {
            totalSum += arr[i];
        }
 
        int leftSum = 0;
        for (int i = 0; i < arr.length; ++i) {
            int rightSum = totalSum - leftSum - arr[i];
 
            if (leftSum == reverseInteger(rightSum)) {
                return i;
            }
            leftSum += arr[i];
        }
 
        return -1;
    }
 
    public static void main(String[] args) {
        int[] arr = {5, 7, 3, 6, 4, 9, 2};
        int index = findIndex(arr);
 
        // Output
        System.out.println(index);
    }
}


Python3




def reverse_integer(n):
    return int(str(n)[::-1])
 
def check_index(arr, index):
    left_sum = sum(arr[:index])
    right_sum = sum(arr[index+1:])
    if left_sum == reverse_integer(right_sum):
        return True
    return False
 
def find_index(arr):
    total_sum = sum(arr)
    left_sum = 0
    for i in range(len(arr)):
        right_sum = total_sum - left_sum - arr[i]
        if left_sum == reverse_integer(right_sum):
            return i
        left_sum += arr[i]
    return -1
 
arr = [5, 7, 3, 6, 4, 9, 2]
index = find_index(arr)
print(index)


C#




using System;
 
class Program
{
    // Function to reverse an integer
    static int ReverseInteger(int n)
    {
        int reversed = 0;
        while (n > 0)
        {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        return reversed;
    }
 
    // Function to check if an index satisfies the condition
    static bool CheckIndex(int[] arr, int index)
    {
        int leftSum = 0;
        for (int i = 0; i < index; ++i)
        {
            leftSum += arr[i];
        }
 
        int rightSum = 0;
        for (int i = index + 1; i < arr.Length; ++i)
        {
            rightSum += arr[i];
        }
 
        if (leftSum == ReverseInteger(rightSum))
        {
            return true;
        }
 
        return false;
    }
 
    // Function to find the index
    static int FindIndex(int[] arr)
    {
        int totalSum = 0;
        for (int i = 0; i < arr.Length; ++i)
        {
            totalSum += arr[i];
        }
 
        int leftSum = 0;
        for (int i = 0; i < arr.Length; ++i)
        {
            int rightSum = totalSum - leftSum - arr[i];
 
            if (leftSum == ReverseInteger(rightSum))
            {
                return i;
            }
            leftSum += arr[i];
        }
 
        return -1;
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 5, 7, 3, 6, 4, 9, 2 };
        int index = FindIndex(arr);
 
        // Output
        Console.WriteLine(index);
    }
}


Javascript




function reverseInteger(n) {
  return parseInt(n.toString().split('').reverse().join(''));
}
 
function checkIndex(arr, index) {
  const leftSum = arr.slice(0, index).reduce((acc, val) => acc + val, 0);
  const rightSum = arr.slice(index + 1).reduce((acc, val) => acc + val, 0);
  if (leftSum === reverseInteger(rightSum)) {
    return true;
  }
  return false;
}
 
function findIndex(arr) {
  const totalSum = arr.reduce((acc, val) => acc + val, 0);
  let leftSum = 0;
  for (let i = 0; i < arr.length; i++) {
    const rightSum = totalSum - leftSum - arr[i];
    if (leftSum === reverseInteger(rightSum)) {
      return i;
    }
    leftSum += arr[i];
  }
  return -1;
}
 
const arr = [5, 7, 3, 6, 4, 9, 2];
const index = findIndex(arr);
console.log(index);


Output

2

Time Complexity: O(NLogN) 
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads