June 24th 2023

Find Pivot Index — Typescript

Problem Description permalink

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Solution permalink

function expect(description: string, test: boolean) {
if (test) {
console.log(`${description}`)
} else {
console.log(`${description}`)
}
}

function sum(arg: number[]): number {
return arg.reduce((sum, i) => sum + i, 0)
}

function pivotIndex(nums: number[]): number {
for (var pivotIndex = 0; pivotIndex < nums.length; pivotIndex++) {
const leftSide = nums.slice(0, pivotIndex)
const rightSide = nums.slice(pivotIndex + 1)
if (sum(leftSide) == sum(rightSide)) {
return pivotIndex
}
}
return -1
};

expect("simple example", pivotIndex([1, 7, 3, 6, 5, 6]) == 3)
expect("no index", pivotIndex([1, 2, 3]) == -1)
expect("position 0", pivotIndex([2, 1, -1]) == 0)

Discussion permalink

This is not the fastest way. This is slower, at the expense of being clear and easily debuggable. Would I ship this? As with all of these problems- it depends. If this function was dealing with small amounts of data or was run in a non-cost sensitive job- yes, very much. If this was in the hot spot in the code like a request/response cycle then very very much no.