Pankaj Tanwar
Published on

Find the Middle Index in Array.

––– views
Authors

Problem of the day - Find the Middle Index in Array

Tag - Easy

Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).

A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].

If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.

Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.

Example 1:

Input: nums = [2,3,-1,8,4] Output: 3 Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 The sum of the numbers after index 3 is: 4 = 4


Problem is pretty simple. For each index, we just need to check if sum of the left side element and right side elements is equal, just return the current index otherwise return -1.

There are multiple ways to find the sum of left and right elements. Worst approach would be to calculate this, for each element by going left and right.

One of the good approach, I could think of to calculate total sum in one time and keep on subtracting the sum till current index to get diff.

Here is the code

class Solution {
public:
int findMiddleIndex(vector<int>& nums) {
int total = 0;
int sum_till = 0;
// total sum
for(auto val: nums) total += val;
for(int i=0;i<nums.size();i++) {
// if sum till now (left sum), is equal to total - sum till now - (means right sum)
if(sum_till == total - sum_till - nums[i]) return i;
sum_till += nums[i];
}
return -1;
}
};

If you feel, I am missing on something, feel free to reach out to me


I welcome your suggestions to improve it further!


Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.


You might like previous editions of my coding diary