easyArraysPattern: Prefix Sum

Find Balance Index Solution

Problem Statement

You are given an array of integers `elements`. Find the index where the total sum of elements before it equals the total sum of elements after it. Return -1 if no such index exists.

Examples

Example 1:
Input:[1, 7, 3, 6, 5, 6]
Output:3
Explanation: Total deliveries before index 3 (1 + 7 + 3 = 11) equals total deliveries after index 3 (5 + 6 = 11)
Example 2:
Input:[1, 2, 3]
Output:-1
Explanation: No such index exists where total deliveries before it equals total deliveries after it

Constraints

  • 1 <= n <= 10^4
  • -1000 <= arr[i] <= 1000
Time: O(N) Space: O(1)
Use a single pass to calculate the total sum and then find the pivot index in O(n) time complexity

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.