2Brute2Best
🔥0
05

Prefix + suffix (Prefix Sum Sub-pattern)

Each index needs something from everything on its left and everything on its right. Make one pass from the left, one from the right, then combine.

Signals in the problem statement
  • ›

    "sum of elements to the left / right of i"

  • ›

    "product of all elements except self"

  • ›

    "best split point", "best hour to close"

What makes it different

No searching — every index gets an answer. What the right side needs decides how much work it is: for sums, the right side is just total − left − nums[i], so one running value is enough. Products can't be undone (dividing by 0), so they need a real second pass from the right. When each side counts something different (closed hours with customers vs open hours without), keep a running score that changes by ±1 as the split point moves.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Find Pivot Index
    Basic Anchor·LeetCode #724
    Easy
  2. 2
    Left and Right Sum Differences
    Basic Reinforcement·LeetCode #2574
    Easy
  3. 3
    Product of Array Except Self
    Medium·LeetCode #238
    Medium
  4. 4
    Minimum Penalty for a Shop
    Tricky / Edge Case·LeetCode #2483
    Medium

Template

left-right-template.cpp
// For every index, combine what's on its left with what's on its right.
// Example: leftSum[i] - rightSum[i], without building a right array.
vector<long long> leftMinusRight(vector<int>& nums) {
    long long total = 0;
    for (int x : nums) total += x;
    vector<long long> answer(nums.size());
    long long left = 0;                         // sum of nums[0..i-1]
    for (int i = 0; i < (int)nums.size(); i++) {
        long long right = total - left - nums[i];  // sum of nums[i+1..n-1]
        answer[i] = left - right;
        left += nums[i];
    }
    return answer;
}
Remember this · Prefix Sum
Trigger
Range sums, "subarray sum equals K" (especially with negatives), equal counts, divisible by K.
Think
If I knew the total up to every index, would the answer become a difference of two totals?
Key question
Which earlier prefix value am I looking for when I stand at index i?