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;
}
}
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/leetcode/co...