Problem · Array
Balanced Sum
Learn this problemProblem statement
Given an array of numbers, find the 0-based index of the smallest array element (the pivot) where the sum of all elements to the left and to the right are equal. The array may not be reordered.
Function
balancedSum(arr: int[]) → int
Complete the function balancedSum in the editor with the following parameter(s):
int arr[n]: an array of integers
Returns
int: the 0-based index of the pivot
Constraints
- 3≤n≤10^5
- 1≤arr[i]≤2×10^4, where 0≤i
- It is guaranteed that a solution always exists.
Couldn't do it without the help from an incredible friend! 🍊
Examples
Example 1
arr = [1, 2, 3, 4, 6]return = 3The sum of the first three elements is 1 + 2 + 3 = 6.
The value of the last element is 6.
Using zero-based indexing, arr[3]=4 is the pivot between these two subarrays.
Return the index of the pivot, 3.
Example 2
arr = [1, 2, 3, 3]return = 2The sum of the first two elements, 1 + 2 = 3. The value of the last element is 3.
Using 0-based indexing, arr[2] = 3 is the pivot between these two subarrays.
The index of the pivot is 2.