hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Beautiful Index


  • Approach:

    1. Traverse through the given array. Calculate the total sum.

    2. For each i, calculate the sum through ith index. Subtract this sum from the total sum.

    3. If the subtracted sum becomes equal to the sum of till (i - 1)th index, then return the current index.

    4. Else return -1.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(1)


Code [C++]

#include <bits/stdc++.h>

int beautifulIndex(int N, vector<int> A)

{

int tsum = 0, sum = 0;

for(int i=0; i<N; i++) tsum += A[i];

for(int i=0; i<N; i++){

if((tsum - sum) == sum + A[i]) return i + 1;

sum += A[i];

}

return -1;

}