Find Pivot Index: a linear solution

Another LeetCode, right here: https://leetcode.com/problems/find-pivot-index/description/

Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
There is no index that satisfies the conditions in the problem statement.
Note:
The length of nums will be in the range [0, 10000].

Each element nums[i] will be an integer in the range [-1000, 1000].

Given the length of nums as 10000, an N^2 solution becomes a little too much (100,000,000). It will work, but painfully so. There is a better approach if we're willing to use some extra memory:
  1. Have 2 extra arrays, with the same length
  2. One of the arrays will keep track of the sum of the elements from 0..i. I call it SumLeft
  3. The other one will keep track of the sum of the elements from i..N-1. I call it SumRight
  4. Do another final run checking whether SumLeft[i] == SumRight[i]
Due to (1) we know this will be an O(N)-space algorithm. (2) takes 1N. So does (3). And so does (4), for a grand total of O(3N)-time, also known as O(N)-time. For an N=10000, 3N will fly fast. Code is down below, many cheers and hugs! Marcelo


public class Solution
{
public int PivotIndex(int[] nums)
{
if (nums == null || nums.Length == 0) return -1;

int[] sumLeft = new int[nums.Length];
int[] sumRight = new int[nums.Length];

sumLeft[0] = nums[0];
for (int i = 1; i < nums.Length; i++)
sumLeft[i] = sumLeft[i - 1] + nums[i];
sumRight[nums.Length - 1] = nums[nums.Length - 1];
for (int i = nums.Length - 2; i >= 0; i--)
sumRight[i] = sumRight[i + 1] + nums[i];

for (int i = 0; i < nums.Length; i++)
if (sumLeft[i] == sumRight[i]) return i;
return -1;
}
}

Comments

  1. You can avoid an extra pass by exploiting a fact that sumRight[i] = totalSum - sumLeft[i] + nums[i]. You can also use a constant space since at any point of time you only need a single value of sumLeft[i], so you can replace it with a running sum. After these simple optimizations we get O(N) time and O(1) space complexity with:

    class Solution {
    public:
    int pivotIndex(const vector& nums) {
    int sum = accumulate(nums.cbegin(), nums.cend(), 0);
    int runningSum = 0;
    for (int i = 0; i < nums.size(); runningSum += nums[i], i += 1) {
    if (runningSum * 2 == sum - nums[i]) {
    return i;
    }
    }
    return -1;
    }
    };

    Reply Delete
    Replies
    1. a slightly more compact version, since Blogger hates code:

      class Solution {
      public:
      int pivotIndex(const vector& nums) {
      int sum = accumulate(nums.cbegin(), nums.cend(), 0);
      for (int i = 0, runningSum = 0; i < nums.size(); runningSum += nums[i], i += 1) {
      if (runningSum * 2 == sum - nums[i]) return i;
      }
      return -1;
      }
      };

      Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...