Problem Description
Given an integer array, find the pivot index where the sum of all the numbers to the left equals the sum of all the numbers to the right. If no such index exists, return -1.
Key Insights
- Use a prefix sum strategy by first calculating the total sum of the array.
- As you iterate over the array, maintain the sum of numbers seen so far (left sum).
- At any index, the right sum can be derived by subtracting the left sum and the current element from total sum.
- When left sum equals right sum, you've found the pivot index.
- Only one pass through the array is needed, resulting in O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We start by computing the total sum of the array. Then, we use a single loop to traverse the array and maintain a running sum (left sum). For each index, the right sum is computed as total sum minus left sum minus the current element. If the left sum equals the right sum, we return the current index as the pivot index. If no index satisfies this condition, we return -1.