Find the pivot index in Python
In this Answer, we’ll cover three methods to find the pivot index in Python. We’ll begin with the brute-force implementation and move to more efficient approaches afterward.
In this problem, we have to find the index of an array in which the sum of elements to the left and right of the index are equal. If no such index exists, we’ll return -1. This problem is illustrated in the image below:
Note: When all the elements succeeding it add up to
0, index0is the pivot index. When all the elements preceding it add up to0, the last index is the pivot index.
Here’s a summary of each implementation:
Brute-force: The simplest approach that uses nested loops to check every index in the list and checks for a pivot. It calculates the sum of elements to the left and right of each index and checks if they’re equal. If they are, the pivot index has been found.
Prefix sums: This approach optimizes the solution by precomputing the list sum, which means we only iterate through the list once. It will compute the sum to the right of the index by subtracting the left sum and the current element’s value from the total sum.
Two-pointer: This approach optimizes the solution using two pointers, one from the left and the other from the right. It computes the total sum of the list and then initializes the left pointer to
0and the right pointer to the sum. It then iterates through the list once, updating the right pointer by subtracting the current element’s value and checking whether the pivot index is found.
Brute-force implementation
Let’s take a look at the brute-force implementation of this problem:
def bruteforce(data):for i in range(len(data)):left = sum(data[:i])right = sum(data[i+1:])if left == right:return ireturn -1data = [1, 7, 3, 6, 5, 6]pivot = bruteforce(data)if pivot != -1:print(f"Pivot index found {pivot}")else:print("There is no pivot index")
This code is explained below:
Line 1: We define the
bruteforcefunction, which takes data (list of numbers) as a parameter.Line 2: We iterate through the list.
Line 3: We calculate the sum of the elements to the left side of the current index
i.Line 4: We calculate the sum of the elements to the right side of the current index
i.Line 5: If this condition is met, it means that
iis the pivot index.Lines 9–14: The main function to call our function
bruteforce().
Optimized prefix sums implementation
Let’s take a look at the optimized prefix sums implementation:
def prefix(data):total = sum(data)left = 0for i in range(len(data)):right = total - left - data[i]if left == right:return ileft += data[i]return -1data = [1, 7, 3, 6, 5, 6]pivot = prefix(data)if pivot != -1:print(f"Pivot index found {pivot}")else:print("There is no pivot index")
The code can be explained as follows:
Line 1: We define the
prefixfunction, which takes data (list of numbers) as a parameter.Line 2: We take the
sumof the list and store it intotal.Line 3: We initialize the variable
leftto0. This keeps track of the sum of elements to the left of the index while we iterate through the list.Line 4: We iterate through the list. By using this
forloop withrange(len(data)), the code processes each element in thedatalist, allowing it to calculate the left and right sums and determine if a pivot index exists.Line 5: We calculate the sum values toward the right of the index.
Lines 6–7: We compare the values of
leftandrightsum. If this condition is met, it means thatiis the pivot index.Line 9: If no pivot index is found, we return
-1.Lines 12–17: The main function to call our function
prefix().
Two-pointer implementation
Let’s take a look at the two-pointer implementation:
def pointer(data):left = 0right = sum(data)for i in range(len(data)):right -= data[i]if left == right:return ileft += data[i]return -1data = [1, 7, 3, 6, 5, 6]pivot = pointer(data)if pivot != -1:print(f"Pivot index found {pivot}")else:print("There is no pivot index")
The code can be explained as follows:
Line 1: We define the
pointerfunction, which takes data (list of numbers) as a parameter.Lines 2–3: We initialize
leftto0andrightto thesumof the elements indata.Line 5: We iterate through the list using the same
forloop in the previous implementation.Lines 6–8: We subtract the value in
data[i]from therightvariable. Afterward, we’ll check ifleftis equal torightand if they are, theniis the pivot index.Line 9: If they aren’t equal, we update the
leftvalue by adding the next element to the list.
Quiz
What is the purpose of finding a pivot index in an array?
To sort the array efficiently.
To find an index where elements to the left and right have equal sums.
To find the maximum value in the array.
Free Resources