Leetcode: Find Pivot Index
Kotlin

Leetcode: Find Pivot Index

2024-03-20
10 min read

Leetcode — Find Pivot Index (Java)

Leetcode: Find Pivot Index is an easy question in the Leetcode 75 study plan. I will walk through my approach to solving this in Java.

Problem Statement

Examples

Constraints

Brainstorm

My first idea to tackle this was to use two pointers on the starting and last index of the array.

We could have left = 0, right = nums.length-1, leftSum = 0, and rightSum = nums.length-1. If leftSum is greater than rightSum add to leftSum and increment left. If rightSum is greater than leftSum add to rightSum and decrement right. This solution gets messy when you encounter the edge cases such as returning the index if

The second approach would be to get the total sum of all the numbers in the nums array. We can then loop through the array and have another sum variable to add the sum of the array. We can call this the left sum. On each iteration, we can then subtract the total sum from (left sum + the current number), to get the right side. If the difference (right sum) is equal to our left sum, then we have found the pivot index, so we can return i

Solution:

{% gist https://gist.github.com/cmcoffeedev/50dcad91cd08728af9fc46ec9d615e77.js %}