#3862

Find the Smallest Balanced Index

Medium
ArrayPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use prefix sums for left sums and suffix products for right products to efficiently determine balanced indices in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate prefix sums for left sums in a single pass.
  2. 2Step 2: Calculate suffix products for right products in reverse.
  3. 3Step 3: Compare left sums and right products to find the smallest balanced index.
solution.py11 lines
1def smallestBalancedIndex(nums):
2    n = len(nums)
3    left_sum = [0] * n
4    for i in range(1, n):
5        left_sum[i] = left_sum[i - 1] + nums[i - 1]
6    right_product = 1
7    for i in range(n - 1, -1, -1):
8        if left_sum[i] == right_product:
9            return i
10        right_product *= nums[i]
11    return -1

Complexity note: We traverse the array twice: once for prefix sums and once for suffix products, leading to linear complexity.

  • 1Prefix sums help in calculating left sums efficiently.
  • 2Suffix products allow for quick right product calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.