Skip to content

Commit

Permalink
Added subarray sum solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 27, 2024
1 parent 568b0ce commit 9c50202
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ programming challenges completed in other languages.
- [Max Chunks to Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted)
- [Valid Sudoku](https://leetcode.com/problems/valid-sudoku)
- [Merge Nodes In Between Zeroes](https://leetcode.com/problems/merge-nodes-in-between-zeros/)
- [Minimum Size SubArray](https://leetcode.com/problems/minimum-size-subarray-sum)

#### Hard

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,4 @@ mod smallest_letter;
mod negative_numbers;
mod guess_number;
mod merge_nodes;
mod subarray_sum;
30 changes: 30 additions & 0 deletions src/leetcode/subarray_sum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub fn min_sub_array_len(target: i32, numbers: Vec<i32>) -> i32 {
let (mut left, mut right) = (0, 0);
let mut sum = 0;
let mut min_len = usize::MAX;
while right < numbers.len() {
sum += numbers[right];
right += 1;

while sum >= target {
min_len = std::cmp::min(min_len, right - left);
sum -= numbers[left];
left += 1;
}
}

match min_len == usize::MAX {
true => 0,
false => min_len as i32,
}
}

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

#[test]
fn finds_length_of_smallest_subarr_that_sums_to_target() {
assert_eq!(2, min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3]))
}
}

0 comments on commit 9c50202

Please sign in to comment.