Skip to content

Commit b2967d4

Browse files
solves find the middle index in array
1 parent 1be1669 commit b2967d4

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@
476476
| 1974 | [Minimum Time to Type Word Using Special Typewriter](https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter) | [![Java](assets/java.png)](src/MinimumTimeToTypeWordUsingSpecialTypewriter.java) | |
477477
| 1979 | [Find Greatest Common Divisor of Array](https://leetcode.com/problems/find-greatest-common-divisor-of-array) | [![Java](assets/java.png)](src/FindGreatestCommonDivisorOfArray.java) | |
478478
| 1984 | [Minimum Difference Between Highest and Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores) | [![Java](assets/java.png)](src/MinimumDifferenceBetweenHighestAndLowestOfKScores.java) | |
479-
| 1991 | [Find the Middle Index in Array](https://leetcode.com/problems/find-the-middle-index-in-array) | | |
479+
| 1991 | [Find the Middle Index in Array](https://leetcode.com/problems/find-the-middle-index-in-array) | [![Java](assets/java.png)](src/FindTheMiddleIndexInArray.java) | |
480480
| 1995 | [Count Special Quadruplets](https://leetcode.com/problems/count-special-quadruplets) | | |
481481
| 2000 | [Reverse Prefix of Word](https://leetcode.com/problems/reverse-prefix-of-word) | | |
482482
| 2006 | [Count Number of Pairs With Absolute Difference K](https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k) | | |

Diff for: src/FindTheMiddleIndexInArray.java

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// https://leetcode.com/problems/find-the-middle-index-in-array
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.Arrays;
6+
7+
public class FindTheMiddleIndexInArray {
8+
public int findMiddleIndex(int[] nums) {
9+
int leftSum = 0, rightSum = Arrays.stream(nums).sum() - nums[0];
10+
if (leftSum == rightSum) return 0;
11+
for (int index = 1 ; index < nums.length ; index++) {
12+
rightSum -= nums[index];
13+
leftSum += nums[index - 1];
14+
if (leftSum == rightSum) return index;
15+
}
16+
return -1;
17+
}
18+
}

0 commit comments

Comments
 (0)