Find pivot in array where left sum is equal to right sum in JavaScript

0

Solution with n2 complexity

let arr = [1,2,3,3,4,5,4,4,5];

for(let i =0; i < arr.length; i++){
  if(ispivot(i,arr)){
    console.log(arr[i],"this is pivot");
  }
}

function ispivot(pointer,arr){
  let leftsum = 0;
  let rightsum = 0;
  for(let i =0 ; i < pointer;i++){
    leftsum = leftsum+arr[i];
  }
  for(let j = pointer+1; j<arr.length; j++){
    rightsum = rightsum+arr[j];
  }
  if(rightsum == leftsum){
    return true;
  }
  return false;
}

Solution with nlogn complexity

let arr = [1,2,3,3,4,5,4,4,5];
let leftsum = 0;
for(let i =0; i < arr.length; i++){
  
  if(ispivot(i,arr,leftsum)){
    console.log(arr[i],"this is pivot");
  }
  leftsum= leftsum+arr[i];
}

function ispivot(pointer,arr, leftsum){
  // let leftsum = 0;
  let rightsum = 0;
  // for(let i =0 ; i < pointer;i++){
  //   leftsum = leftsum+arr[i];
  // }
  for(let j = pointer+1; j<arr.length; j++){
    rightsum = rightsum+arr[j];
  }
  if(rightsum == leftsum){
    return true;
  }
  return false;
}

Solution with 3n (On) complexity

let arr = [1,2,3,3,4,5,4,4,5];
let leftsum = 0;
let leftsumarray = [];
let rightsum = 0;
let rightsumarray = [];
for(let i =0; i < arr.length; i++){
  leftsumarray.push(leftsum);
  leftsum= leftsum+arr[i];
}
for(let j =arr.length-1; j >=0; j--){
  rightsumarray.push(rightsum);
  rightsum= rightsum+arr[j];
}
for(let k =0; k < arr.length; k++){
  if(leftsumarray[k] == rightsumarray[arr.length - k -1]){
    console.log("Pivot is : "+arr[k]);
  }
}

Leave a Comment

Skip to content