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
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: 2
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.
- Iterate through the vector using a for loop with an index i from 0 to n-1.
- 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.
- 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.
- Convert the result from step 3 to a string and store in variable sum_r_str
- Reverse the string from step 4 and store it in variable sum_r_str_reversed
- Compare sum_l from step 2 with the result of the string from step 5, stoi(sum_r_str_reversed)
- If the comparison is true, print i and return 0, otherwise continue with the for loop.
- 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 );
}
}
|
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 );
|
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);
}
}
|
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);
|
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++
#include <bits/stdc++.h>
using namespace std;
bool checkReverse( int leftSum, int rightSum)
{
int rev = 0;
int temp = rightSum;
while (temp != 0) {
rev = (rev * 10) + (temp % 10);
temp /= 10;
}
if (rev == leftSum) {
return true ;
}
return false ;
}
int findIndex( int arr[], int N)
{
int rightSum = 0;
int leftSum = 0;
for ( int i = 0; i < N; i++) {
rightSum += arr[i];
}
for ( int i = 0; i < N; i++) {
rightSum -= arr[i];
if (checkReverse(leftSum,
rightSum)) {
return i;
}
leftSum += arr[i];
}
return -1;
}
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
import java.util.*;
class GFG {
static boolean checkReverse( int leftSum, int rightSum)
{
int rev = 0 ;
int temp = rightSum;
while (temp != 0 ) {
rev = (rev * 10 ) + (temp % 10 );
temp /= 10 ;
}
if (rev == leftSum) {
return true ;
}
return false ;
}
static int findIndex( int [] arr, int N)
{
int rightSum = 0 ;
int leftSum = 0 ;
for ( int i = 0 ; i < N; i++) {
rightSum += arr[i];
}
for ( int i = 0 ; i < N; i++) {
rightSum -= arr[i];
if (checkReverse(leftSum,
rightSum)) {
return i;
}
leftSum += arr[i];
}
return - 1 ;
}
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));
}
}
|
Python3
def checkReverse(leftSum, rightSum):
rev = 0
temp = rightSum
while (temp ! = 0 ):
rev = (rev * 10 ) + (temp % 10 )
temp / / = 10
if (rev = = leftSum):
return True
return False
def findIndex(arr, N):
rightSum = 0
leftSum = 0
for i in range (N):
rightSum + = arr[i]
for i in range (N):
rightSum - = arr[i]
if (checkReverse(leftSum, rightSum)):
return i
leftSum + = arr[i]
return - 1
if __name__ = = '__main__' :
arr = [ 5 , 7 , 3 , 6 , 4 , 9 , 2 ]
N = len (arr)
print (findIndex(arr, N))
|
C#
using System;
class GFG {
static bool checkReverse( int leftSum, int rightSum)
{
int rev = 0;
int temp = rightSum;
while (temp != 0) {
rev = (rev * 10) + (temp % 10);
temp /= 10;
}
if (rev == leftSum) {
return true ;
}
return false ;
}
static int findIndex( int [] arr, int N)
{
int rightSum = 0;
int leftSum = 0;
for ( int i = 0; i < N; i++) {
rightSum += arr[i];
}
for ( int i = 0; i < N; i++) {
rightSum -= arr[i];
if (checkReverse(leftSum,
rightSum)) {
return i;
}
leftSum += arr[i];
}
return -1;
}
static void Main()
{
int [] arr = { 5, 7, 3, 6, 4, 9, 2 };
int N = arr.Length;
Console.Write(findIndex(arr, N));
}
}
|
Javascript
<script>
function checkReverse(leftSum , rightSum) {
var rev = 0;
var temp = rightSum;
while (temp != 0) {
rev = (rev * 10) + (temp % 10);
temp = parseInt(temp/10);
}
if (rev == leftSum) {
return true ;
}
return false ;
}
function findIndex(arr , N) {
var rightSum = 0;
var leftSum = 0;
for (i = 0; i < N; i++) {
rightSum += arr[i];
}
for (i = 0; i < N; i++) {
rightSum -= arr[i];
if (checkReverse(leftSum, rightSum)) {
return i;
}
leftSum += arr[i];
}
return -1;
}
var arr = [ 5, 7, 3, 6, 4, 9, 2 ];
var N = arr.length;
document.write(findIndex(arr, N));
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int reverseInteger( int n) {
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
bool checkIndex(vector< 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.size(); ++i) {
rightSum += arr[i];
}
if (leftSum == reverseInteger(rightSum)) {
return true ;
}
return false ;
}
int findIndex(vector< int >& arr) {
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 (leftSum == reverseInteger(rightSum)) {
return i;
}
leftSum += arr[i];
}
return -1;
}
int main() {
vector< int > arr = {5, 7, 3, 6, 4, 9, 2};
int index = findIndex(arr);
cout << index << std::endl;
return 0;
}
|
Java
public class Main {
static int reverseInteger( int n) {
int reversed = 0 ;
while (n > 0 ) {
reversed = reversed * 10 + n % 10 ;
n /= 10 ;
}
return reversed;
}
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);
}
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);
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
{
static int ReverseInteger( int n)
{
int reversed = 0;
while (n > 0)
{
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
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 ;
}
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;
}
static void Main()
{
int [] arr = { 5, 7, 3, 6, 4, 9, 2 };
int index = FindIndex(arr);
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
Share your thoughts in the comments
Please Login to comment...