code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

724 Find Pivot Index

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const findPivotIndex = nums => {
  let leftSum = 0
  const total = nums.reduce((a, b) => a + b, 0)
  for (let i = 0; i < nums.length; i++) {
    const rightSum = total - nums[i] - leftSum
    if (rightSum == leftSum) {
      return i
    }
    leftSum += nums[i]
  }
  return -1
}

console.log(findPivotIndex([1, 7, 3, 6, 5, 6]))

Created 2022-03-21T11:17:20+00:00 · Edit