Skip to content

Latest commit

 

History

History
46 lines (30 loc) · 627 Bytes

File metadata and controls

46 lines (30 loc) · 627 Bytes

Pivot Index

Problem Link

https://leetcode.com/problems/find-pivot-index/


Pattern

  • Prefix Sum

Approach

Compute total sum, then iterate tracking left sum. Pivot where left == total - left - nums[i].


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

class Solution {
    public int pivotIndex(int[] nums) {
        int total = 0;
        for (int n : nums) total += n;
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            if (left == total - left - nums[i]) return i;
            left += nums[i];
        }
        return -1;
    }
}