45 Days of Leetcode - Find Pivot Index - Day 3.1
Anas Dew
Posted on December 19, 2022
Hey dev! In case you don't know, I've started #45daysofleetcode and in these 45 days i'll be writing about two problems every day.
The problem, how I solved it and a bit of detailed explanation.
I'm sharing this progress with you so that you too can learn a bit of different perspective and have new solutions so hit like to join this journey.
I've chosen the best list of problems from medium to hard. That made lots of developers crack the interview.
Are you excited?
Today's Problem
Name
Find Pivot Index
Description
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.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example
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
My Approach
We will iterate through the array, and at each index, we check if the sum of the left side of the index is equal to the sum of the right side of the index.
Code
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total_sum, right_sum, left_sum = sum(nums), 0, 0
for i in range(len(nums)):
right_sum = total_sum - nums[i] - left_sum
if left_sum == right_sum:
return i
left_sum += nums[i]
return -1
Let me know if you've any questions or suggestions!.
If you want full list of solutions, here's the list. Make sure you star the repository.
Follow to join this #45daysofleetcode
Bye!
Posted on December 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.