Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

724. Find Pivot Index

Given array nums, return the leftmost pivot index where sum of elements to the left equals sum of elements to the right. Return -1 if none exists.

Approach: compute total sum upfront, then walk left to right tracking running left sum; right sum derived as total - left_sum - nums[i].

#![allow(unused)]
fn main() {
// time O(n), space O(1)
pub fn pivot_index(nums: Vec<i32>) -> i32 {
    let total: i32 = nums.iter().sum();
    let mut left_sum = 0;
    for i in 0..nums.len() {
        let right_sum = total - left_sum - nums[i];
        if left_sum == right_sum {
            return i as i32;
        }
        left_sum += nums[i];
    }

    -1
}
}