Skip to the code
cf.
+10 XP

#39 Balance Point of a Toolbar

easy

A designer wants to split a toolbar so the items left of a chosen item are exactly as wide in total as the items to its right. The item widths are in widths.

Write balancePoint(widths) that returns the smallest index i where the sum of widths[0..i - 1] equals the sum of widths[i + 1..]. The chosen item itself is on neither side, and an empty side sums to 0. Return -1 if no index works.

Example 1

Input: widths = [1,4,2,3,2]
Output: 2

Left of index 2 is 1 + 4 = 5; right of it is 3 + 2 = 5.

Example 2

Input: widths = [1,2,3]
Output: -1

No index has equal sums on both sides.

Constraints

  • 0 <= widths.length <= 10^5
  • -1000 <= widths[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).