Skip to content

Commit

Permalink
Add problem 1991: Find the Middle Index in Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 6, 2023
1 parent 0d2afe4 commit cba9762
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1378,6 +1378,7 @@ pub mod problem_1979_find_greatest_common_divisor_of_array;
pub mod problem_1980_find_unique_binary_string;
pub mod problem_1984_minimum_difference_between_highest_and_lowest_of_k_scores;
pub mod problem_1985_find_the_kth_largest_integer_in_the_array;
pub mod problem_1991_find_the_middle_index_in_array;

#[cfg(test)]
mod test_utilities;
39 changes: 39 additions & 0 deletions src/problem_1991_find_the_middle_index_in_array/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn find_middle_index(nums: Vec<i32>) -> i32 {
let total_sum = nums.iter().sum::<i32>();
let mut result = -1;
let mut sum = 0;

for (i, num) in (0..).zip(nums) {
if sum + sum + num == total_sum {
result = i;

break;
}

sum += num;
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn find_middle_index(nums: Vec<i32>) -> i32 {
Self::find_middle_index(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_1991_find_the_middle_index_in_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn find_middle_index(nums: Vec<i32>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [(&[2, 3, -1, 8, 4] as &[_], 3), (&[1, -1, 4], 2), (&[2, 5], -1)];

for (nums, expected) in test_cases {
assert_eq!(S::find_middle_index(nums.to_vec()), expected);
}
}
}

0 comments on commit cba9762

Please sign in to comment.