Coming soon - Get a detailed view of why an account is flagged as spam!
view details
2
Leetcode 724 - Find Pivot Index - Java - Getting Wrong Answer
Author Summary
WildAlcoholic is age 72
Post Body

Hi all,

I'm currently solving Leetcode 724 and I can't seem to get the right answer. On paper, my algorithm seems to make sense. Can anyone help me spot where i'm going wrong?

My algorithm is as follows:

Iterate through the array from left to right, advancing a "pointer" that potentially can be the pivot index.

On each iteration, calculate the sum of the left sub-array, calculate the sum of the right sub-array, and compare if they are equal.

If the sum of the left sub-array and the right sub-array are equal, return the index of the element currently being iterated on as this is the pivot index.

If we reach the end of the loop and no such index exists, exit the loop and return negative 1. Meaning there is no pivot index in the input array.

When I run the code below, Leetcode says:

Wrong AnswerYour Input: [1,7,3,6,5,6]Output: -1Expected: 3

Note: I have implemented and understand the more O(n) optimal solution to this problem. I would like to understand and implement the O(n^2) solution for my own sanity.

Thanks in advance!

class Solution {
    public int pivotIndex(int[] nums) {

        for(int i = 0; i < nums.length; i  ){
            int left = calculateLeftSum(nums, i - 1);
            int right = calculateRightSum(nums, i   1);

            if(left == right){
                return i;
            }
        }
        return -1; 
    }

    public static int calculateLeftSum(int[] arr, int endIndex){
        int leftSum = 0;

        if(endIndex <= 0){
            return 0;
        }

        for(int j = 0; j < endIndex; j  ){
            leftSum  = arr[j];
        }

        return leftSum; 
    }

    public static int calculateRightSum(int[] arr, int startIndex){
        int rightSum = 0;

        for(int k = startIndex; k < arr.length; k  ){
            rightSum  = arr[k];
        }

        return rightSum;
    }
}

Author
Account Strength
100%
Account Age
2 years
Verified Email
Yes
Verified Flair
No
Total Karma
16,798
Link Karma
1,926
Comment Karma
14,334
Profile updated: 5 days ago
Posts updated: 6 months ago

Subreddit

Post Details

Age
72
We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
2 years ago