-
Notifications
You must be signed in to change notification settings - Fork 18
/
724.Find-Pivot-Index.js
38 lines (35 loc) · 1010 Bytes
/
724.Find-Pivot-Index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Linear Search
* Running Pointers Algorithms
* Time O(N) | Space O(1)
* https://leetcode.com/problems/find-pivot-index/
* @param {number[]} nums
*
*
- traverse the elements - Linear loop(for loop) and get the total sum
- to calculate the right sum, compute below formula
(rightSum = totalSum - leftSum - current nums at index)
- this formala helps exclude the left sum and pivot index num to get the right sum
- if condition allows us to compare the left and right sum
*/
//Optimal Solution
const pivotIndex = (nums) => {
const len = nums.length;
let total = 0;
let leftSum = 0;
for (let i = 0; i < len; i++) {
total += nums[i];
}
for (let i = 0; i < len; i++) {
rightSum = total - leftSum - nums[i];
if (rightSum === leftSum) {
return i;
}
leftSum = leftSum + nums[i];
}
return -1;
};
module.exports = pivotIndex;
console.log(pivotIndex([1,7,3,6,5,6])) //3
console.log(pivotIndex([1,2,3])) //-1
console.log(pivotIndex([2,1,-1])) //0