Skip to content

Commit

Permalink
180th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Jul 27, 2024
1 parent 134b4df commit 0199484
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@ Ace Coding Interview with 75 Qs
| Prefix Sum | | |
| ------------------------------- | ---------------- | ---- |
| 1732. Find the Highest Altitude | [Solution][1732] | Easy |
| 724. Find Pivot Index | Solution | Easy |
| 724. Find Pivot Index | [Solution][724] | Easy |

[1732]: ./src/page-16/1732.%20Find%20the%20Highest%20Altitude/largestAltitude.ts
[724]: ./src/page-7/724.%20Find%20Pivot%20Index/pivotIndex.ts

| Hash Map / Set | | |
| ---------------------------------------- | -------- | ------ |
Expand Down
9 changes: 9 additions & 0 deletions src/page-7/724. Find Pivot Index/pivotIndex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { pivotIndex } from './pivotIndex';

describe('724. Find Pivot Index', () => {
test('pivotIndex', () => {
expect(pivotIndex([1, 7, 3, 6, 5, 6])).toBe(3);
expect(pivotIndex([1, 2, 3])).toBe(-1);
expect(pivotIndex([2, 1, -1])).toBe(0);
});
});
23 changes: 23 additions & 0 deletions src/page-7/724. Find Pivot Index/pivotIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type PivotIndex = (nums: number[]) => number;

/**
* Accepted
*/
export const pivotIndex: PivotIndex = (nums) => {
// Calculate the total sum of the array
const totalSum = nums.reduce((acc, num) => acc + num, 0);

// Initialize the left sum as 0
let leftSum = 0;

for (let i = 0; i < nums.length; i++) {
// Check if the left sum is equal to the right sum
if (leftSum === totalSum - leftSum - nums[i]) return i;

// Update the left sum by adding the current element
leftSum += nums[i];
}

// If no pivot index is found, return -1
return -1;
};

0 comments on commit 0199484

Please sign in to comment.