Equilibrium Index
JavaScript
Medium
5 views
Problem Description
Find an index i such that sum of left side equals sum of right side. Print smallest such index, else -1.
Input Format
One line: n then n integers.
Output Format
One integer index.
Official Solution
const fs=require('fs');const p=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!p[0])process.exit(0);let i=0;const n=Number(p[i++]);let arr=new Array(n);let total=0n;for(let j=0;j<n;j++){arr[j]=BigInt(p[i++]);total+=arr[j];}let left=0n;let ans=-1;for(let j=0;j<n;j++){const right=total-left-arr[j];if(left===right){ans=j;break;}left+=arr[j];}process.stdout.write(String(ans));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!