To find pivot point in an array, we need to iterate through the elements of the array and check for each element whether the sum of elements on its left is equal to the sum of elements on its right. If we find such an element, we return its index as the pivot point. Otherwise, we return -1 to indicate that there is no pivot point in the array.
Here is the code to find pivot point in javascript:
index.tsx263 chars13 lines
We start by initializing leftSum
to 0 and rightSum
to the sum of all elements in the array using the reduce
method. Then we iterate through the array using for
loop and for each element, we subtract it from rightSum
and check if leftSum
is equal to rightSum
. If it is, we return the index of that element as the pivot point. Otherwise, we add the element to leftSum
and continue the loop. If we reach the end of the loop without finding any pivot point, we return -1.
gistlibby LogSnag