
Problem
Solution
Submissions
Pivot Index
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a Java program to find the pivot index of an 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 right of the index. If such an index does not exist, return -1. If there are multiple pivot indexes, return the leftmost pivot index.
Example 1
- Input: nums = [1, 7, 3, 6, 5, 6]
- Output: 3
- Explanation:
- Step 1: Calculate the total sum of all elements in the array: 1 + 7 + 3 + 6 + 5 + 6 = 28.
- Step 2: Initialize leftSum = 0 and rightSum = totalSum - nums[0] = 28 - 1 = 27.
- Step 3: For index 0: leftSum = 0, rightSum = 27, not equal, so not a pivot index.
- Step 4: For index 1: leftSum = 1, rightSum = 27 - 7 = 20, not equal, so not a pivot index.
- Step 5: For index 2: leftSum = 1 + 7 = 8, rightSum = 20 - 3 = 17, not equal, so not a pivot index.
- Step 6: For index 3: leftSum = 8 + 3 = 11, rightSum = 17 - 6 = 11, which are equal, so index 3 is the pivot index.
Example 2
- Input: nums = [1, 2, 3]
- Output: -1
- Explanation:
- Step 1: Calculate the total sum of all elements in the array: 1 + 2 + 3 = 6.
- Step 2: Initialize leftSum = 0 and rightSum = totalSum - nums[0] = 6 - 1 = 5.
- Step 3: For index 0: leftSum = 0, rightSum = 5, not equal, so not a pivot index.
- Step 4: For index 1: leftSum = 1, rightSum = 5 - 2 = 3, not equal, so not a pivot index.
- Step 5: For index 2: leftSum = 1 + 2 = 3, rightSum = 3 - 3 = 0, not equal, so not a pivot index.
- Step 6: No pivot index found, so return -1.
Constraints
- 1 ≤ nums.length ≤ 10^4
- -1000 ≤ nums[i] ≤ 1000
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Calculate the total sum of the array
- Iterate through the array while keeping track of the sum of elements to the left of the current index
- For each index, calculate the sum to the right by subtracting the left sum and the current element from the total sum
- If the left sum equals the right sum, return the current index as the pivot index
- If no pivot index is found after iterating through the array, return -1