Find the Equilibrium Index of an Array

Implement findEquilibriumIndex

Given an array nums, find the leftmost index where the sum of every element strictly to its left equals the sum of every element strictly to its right — an equilibrium indexEquilibrium IndexAn index that splits the array into two parts (excluding the index itself) whose sums are equal. At index 0 the left part is empty (sum 0); at the last index the right part is empty.. Return -1 if none exists. Recomputing both sums from scratch for every candidate index wastes the fact that they barely change between consecutive candidates. Compute the array's total sum once, and the right-hand sum at any index can be derived instantly as total - leftSum - nums[i] — turning an O(n²) scan into a single O(n) pass.

Example 1:

Input: nums = [1,7,3,6,5,6]

Output: 3

Example 2:

Input: nums = [1,2,3]

Output: -1

Example 3:

Input: nums = [2,1,-1]

Output: 0

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁴
  • -1000 ≤ nums[i] ≤ 1000

nums =

[1, 7, 3, 6, 5, 6]