Balanced Index
You are given a 0-indexed array of positive integers, nums.
Your task is to find the first (smallest) index i where the sum of all elements strictly to its left is exactly equal to the product of all elements strictly to its right. For the first element (i = 0), the left sum defaults to 0, and for the last element (i = nums.length - 1), the right product defaults to 1.
Return this index i. If no such index satisfies the condition, return -1.
Example 1:
Input: nums = [1, 99]
Output: 1
Explanation: We evaluate the indices starting from the left. For index 0, the left sum is 0 (because there are no elements before it) and the right product is 99, which do not match. Moving to index 1, the sum of the elements strictly to its left is just the single element 1. The right side of index 1 is completely empty, meaning the right product defaults to 1. Since the left sum equals the right product, 1 is our balanced index.
Example 2:
Input: nums = [3, 5, 7, 2, 4]
Output: 2
Explanation: Checking each index sequentially, we find our first valid match at index 2 (the element 7). The sum of all elements strictly to the left of this index is 3 + 5 = 8. The product of all elements strictly to its right is 2 * 4 = 8. Because the left sum perfectly equals the right product, index 2 satisfies the condition. Since neither index 0 nor index 1 were balanced, 2 is confirmed as the smallest balanced index.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [1, 1, 1, 1]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 109