Find the Leftmost Middle Index in Array

Easy
2
42.3% Acceptance

In this lab, you are required to implement a function that finds the leftmost middle index in a given array. The function should be called findMiddleIndex and take a single parameter:

  • nums (0-indexed): An integer array, where 1 <= nums.length <= 100 and -1000 <= nums[i] <= 1000.

A middleIndex is an index where the sum of all elements before the index (excluding the element at the index) is equal to the sum of all elements after the index (excluding the element at the index). If the index is 0, the left side sum is considered to be 0. Similarly, if the index is at nums.length - 1, the right side sum is considered to be 0.

The function should return the leftmost middle index that satisfies the condition. If there is no such index, return -1.

Examples

Example 1:

const nums = [2, 3, -1, 8, 4]; console.log(findMiddleIndex(nums)); // 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

Example 2:

const nums = [1, -1, 4]; console.log(findMiddleIndex(nums)); // Output: 2

Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0 The sum of the numbers after index 2 is: 0

Example 3:

const nums = [2, 5]; console.log(findMiddleIndex(nums)); // Output: -1

Explanation: There is no valid middleIndex.

Challenges

  1. Write the findMiddleIndex function that correctly finds the leftmost middle index in the array and returns the value as per the given definition. Do not forget to export the function.

  2. Test the findMiddleIndex function with various input arrays to ensure its correctness and consistency.

Please follow the provided instructions, and make sure your code is bug-free. Good luck!