Find Pivot Index
LeetCode: Find Pivot Index
Problem:
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
- Note:
1. The length of nums will be in the range [0, 10000].
2. Each element nums[i] will be an integer in the range [-1000, 1000].
- Examples:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Note:
- Analysis:
Use two sum arrays, left and right.
Left array is to add from [0:i]
Right array to add from [i:len - 1]
Finally, if left[i] == right[i], return the most left index i, otherwise, -1;
- Code - Java:
class Solution {
public int pivotIndex(int[] nums) {
int len = nums.length;
if (len == 0) {
return -1;
}
int[] left = new int[len];
int[] right = new int[len];
right[len - 1] = nums[len - 1];
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] + nums[i];
}
left[0] = nums[0];
if (right[0] == left[0]) {
return 0;
}
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] + nums[i];
if (left[i] == right[i]) {
return i;
}
}
return -1;
}
}
- Code - C++:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int len = nums.size();
if (len == 0) {
return -1;
}
vector<int> left(len, 0);
vector<int> right(len, 0);
right[len - 1] = nums[len - 1];
for (int i = len - 2; i >= 0; i--) {
right[i] = right[i + 1] + nums[i];
}
left[0] = nums[0];
if (right[0] == left[0]) {
return 0;
}
for (int i = 1; i < len; i++) {
left[i] = left[i - 1] + nums[i];
if (left[i] == right[i]) {
return i;
}
}
return -1;
}
};
- Code - Python:
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numsLen = len(nums)
if numsLen == 0:
return -1
left = [0 for i in range(numsLen)]
right = [0 for i in range(numsLen)]
right[numsLen - 1] = nums[numsLen - 1]
for i in range(numsLen - 2, -1, -1):
right[i] = right[i + 1] + nums[i]
left[0] = nums[0]
if right[0] == left[0]:
return 0
for i in range(1, numsLen):
left[i] = left[i - 1] + nums[i]
if left[i] == right[i]:
return i
return -1
Time Complexity: O(N), N is the length of the input array
Space Complexity: O(N), N is the length of the input array.