Skip to content

Commit

Permalink
Added summary ranges solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 30, 2024
1 parent 573ddf8 commit 0434865
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ programming challenges completed in other languages.
- [Happy Number](https://leetcode.com/problems/happy-number)
- [Valid Parentheses](https://leetcode.com/problems/valid-parentheses)
- [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii)
- [Summary Ranges](https://leetcode.com/problems/summary-ranges)

#### Medium

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ mod str_pairs;
mod string_compression;
mod subarray_sum;
mod sum_root_to_leaf;
mod summary_ranges;
mod take_gifts;
mod take_k_characters;
mod third_max;
Expand Down
36 changes: 36 additions & 0 deletions src/leetcode/summary_ranges.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub fn summary_ranges(numbers: Vec<i32>) -> Vec<String> {
let n = numbers.len();
let mut result = Vec::new();
let mut i = 0;
while i < n {
let left = numbers[i];
while i < n - 1 && numbers[i] + 1 == numbers[i + 1] {
i += 1;
}
result.push(match left == numbers[i] {
true => format!("{}", left),
false => format!("{}->{}", left, numbers[i]),
});
i += 1;
}
result
}

#[cfg(test)]
mod tests {
use crate::string_vec;

use super::*;

#[test]
fn produces_ranges_of_consecutive_integers() {
assert_eq!(
string_vec!["0->2", "4->5", "7"],
summary_ranges(vec![0, 1, 2, 4, 5, 7])
);
assert_eq!(
string_vec!["0", "2->4", "6", "8->9"],
summary_ranges(vec![0, 2, 3, 4, 6, 8, 9])
)
}
}

0 comments on commit 0434865

Please sign in to comment.