Very easy understandable JAVA solution with O(N) time complexity and O(1) space complexity


  • 1
    J
    class Solution {
        public int pivotIndex(int[] nums) {
            int sum = 0;
           //Get the sum of the array
            for (int i = 0; i < nums.length; i++) {
                sum += nums[i];
            }
            int preSum = 0;
            for (int i = 0; i < nums.length; i++) {
                //if if sum - nums[i] == preSum * 2, mean left sum equals to right sum
                if (sum - nums[i] == preSum * 2) {
                    return i;
                }
                preSum += nums[i];
            }
            //not found the index
            return -1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.