Similar Problems
Similar Problems not available
Find The Pivot Integer - Leetcode Solution
Companies:
LeetCode: Find The Pivot Integer Leetcode Solution
Difficulty: Easy
Topics: math prefix-sum
Problem Statement:
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 all the numbers to the left of the index is equal to the sum of all 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.
Example:
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 the numbers to the right of index 3. Also, 3 is the first index where this occurs.
Solution:
We can begin by calculating the total sum of the array 'nums'. Then, we can loop through the array and at each index 'i', we can calculate the sum of all elements to the left of it as 'left_sum' and the sum of all elements to the right as 'right_sum'.
If 'left_sum' is equal to 'right_sum', we have found our pivot index and we can return 'i'. If no pivot index exists, we can return -1.
The time complexity of this approach is O(n), where 'n' is the length of the array.
Here's the code implementation of above mentioned approach:
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
# calculate total sum of the array
total_sum = sum(nums)
# initialize left_sum and right_sum to 0
left_sum = 0
right_sum = 0
# loop through the array
for i in range(len(nums)):
# calculate sum of all elements to the left of index 'i'
left_sum += nums[i]
# calculate sum of all elements to the right of index 'i'
right_sum = total_sum - left_sum + nums[i]
# check if left_sum is equal to right_sum
if left_sum == right_sum:
return i
# if no pivot index found, return -1
return -1
This code should pass all the test cases on leetcode.
Find The Pivot Integer Solution Code
1