LeetCode 75

Find Pivot Index

Problem
LC 724
Topic
Prefix Sum
File
official75_LC724FindPivotIndex.java
Path
pkg5leetcode/official75/official75_LC724FindPivotIndex.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC724FindPivotIndex.java
Approach
Prefix sum; pivot where left sum equals right sum.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC724FindPivotIndex.java
1package pkg5leetcode.official75;2 3/*4 * Find Pivot Index | LC 7245 * APPROACH: Prefix sum; pivot where left sum equals right sum.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC724FindPivotIndex {9    static int pivotIndex(int[] nums) {10        int total = 0;11        for (int n : nums) total += n;12        int left = 0;13        for (int i = 0; i < nums.length; i++) {14            if (left == total - left - nums[i]) return i;15            left += nums[i];16        }17        return -1;18    }19 20    public static void main(String[] args) {21        check(pivotIndex(new int[]{1,7,3,6,5,6}) == 3, "case1");22        check(pivotIndex(new int[]{1,2,3}) == -1, "case2");23        check(pivotIndex(new int[]{2,1,-1}) == 0, "case3");24        System.out.println("all tests passed");25    }26 27    static void check(boolean cond, String name) {28        if (!cond) throw new AssertionError("FAILED: " + name);29        System.out.println("  PASS " + name);30    }31}