Last Updated: 5 Jan, 2022

Beautiful Index

Easy
Asked in companies
PayPalAppleFacebook

Problem statement

You are given an array ‘A’ of length ‘N’. You say an index ‘i’ is beautiful if the sum of the first ‘i - 1’ elements of the array ‘A’ equals the sum of the last ‘N - i’ elements of the array ‘A’, where ‘i’ is in 1-based indexing. Now you wonder which is the leftmost beautiful index.

Note: If you select the first index, then the sum of the prefix will be ‘0’, and if you select the last index, then the sum of the suffix will be ‘0’.

Note: You have to print the index in 1-based indexing.

For example:

Let’s say the array ‘A’ = [1, 3, 1, 5], then if we select index ‘2’, the sum of the prefix is ‘1’, and the sum of the suffix is 1 + 5 = 6. Since the sum is not the same, hence index ‘2’ is not a beautiful index.
Input Format-
First-line contains ‘T’, denoting the number of Test cases.
For each Test case:
The first line contains an integer, ‘N’, denoting the length of the array ‘A’.
The following line contains an array ‘A’ of ‘N’ space-separated integers.
Output Format-
For each test case, you have to print an integer denoting the leftmost beautiful index. If there are no beautiful indexes, then print ‘-1’.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints -
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^5 
-10^9 <= A[i] <= 10^9, for 1 <= i <= ‘N’
Note- Sum of ‘N’ over all test cases does not exceed 10^5.

Time Limit: 1 sec

Approaches

01 Approach

Approach: For each index, check if it is a beautiful index or not. If it is a beautiful index, print the index else, continue.

 

Algorithm:

  • Create a variable ‘ans’ and initialize it to ‘-1’.
  • Iterate using a for loop from i = ‘0’ to ‘N - 1’.
    • Create two variables, ‘prefixSum’ and ‘suffixSum’ and initialize both of them to ‘0’.
    • Iterate using a for loop from j = ‘0’ to ‘i - 1’.
      • Increment ‘prefixSum’ by A[j].
    • Iterate using a for loop from j = ‘i + 1’ to ‘N - 1’.
      • Increment ‘suffixSum’ by A[j].
    • If ‘prefixSum’ is equal to ‘suffixSum’.
      • Update ‘ans’ to ‘i + 1’.
      • Break.
  • Print ‘ans’.

02 Approach

Approach: We will store the prefix sum and suffix sum of the array ‘A’. Now, we can check if the prefix sum equals the suffix sum in constant time.

 

Algorithm:

  • Create a variable ‘ans’ and initialize it to ‘-1’.
  • Create a variable ‘suffixSum’ and initialize it to the sum of all elements of the array ‘A’.
  • Create a variable ‘prefixSum’ and initialize it to ‘0’.
  • Iterate using a for loop from i = ‘0’ to ‘N - 1’.
    • Decrement ‘suffixSum’ by ‘A[i]’.
    • If prefixSum is equal to suffixSum.
      • Update ‘ans’ to ‘i + 1’.
      • Break.
    • Increment ‘prefixSum’ by ‘A[i].
  • Print ‘ans’.