Find Pivot Index Solution for Wipro
Company: Wipro · Difficulty: Easy · Topics: Array, Prefix Sum
Problem Statement
Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
Examples
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation: The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation: There is no index that satisfies the conditions.
Approach
Prefix Sum Approach (Optimal)
1. Calculate the total sum of the array
2. Iterate through the array, maintaining a left sum
3. For each index, check if left sum equals (total sum - left sum - current element)
4. Return the first index where this condition is met
Time and Space Complexity
- Time Complexity: O(n) - Two passes through the array
- Space Complexity: O(1) - Only using constant extra space