|
| 1 | +/** |
| 2 | + * [1893] Check if All the Integers in a Range Are Covered |
| 3 | + * |
| 4 | + * You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. |
| 5 | + * Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. |
| 6 | + * An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5 |
| 11 | + * Output: true |
| 12 | + * Explanation: Every integer between 2 and 5 is covered: |
| 13 | + * - 2 is covered by the first range. |
| 14 | + * - 3 and 4 are covered by the second range. |
| 15 | + * - 5 is covered by the third range. |
| 16 | + * |
| 17 | + * Example 2: |
| 18 | + * |
| 19 | + * Input: ranges = [[1,10],[10,20]], left = 21, right = 21 |
| 20 | + * Output: false |
| 21 | + * Explanation: 21 is not covered by any range. |
| 22 | + * |
| 23 | + * |
| 24 | + * Constraints: |
| 25 | + * |
| 26 | + * 1 <= ranges.length <= 50 |
| 27 | + * 1 <= starti <= endi <= 50 |
| 28 | + * 1 <= left <= right <= 50 |
| 29 | + * |
| 30 | + */ |
| 31 | +pub struct Solution {} |
| 32 | + |
| 33 | +// problem: https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/ |
| 34 | +// discuss: https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/?currentPage=1&orderBy=most_votes&query= |
| 35 | + |
| 36 | +// submission codes start here |
| 37 | + |
| 38 | +impl Solution { |
| 39 | + pub fn is_covered(ranges: Vec<Vec<i32>>, left: i32, right: i32) -> bool { |
| 40 | + (left..=right).all(|num| ranges.iter().any(|v| (v[0]..=v[1]).contains(&num))) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// submission codes end |
| 45 | + |
| 46 | +#[cfg(test)] |
| 47 | +mod tests { |
| 48 | + use super::*; |
| 49 | + |
| 50 | + #[test] |
| 51 | + fn test_1893_example_1() { |
| 52 | + let ranges = vec![vec![1, 2], vec![3, 4], vec![5, 6]]; |
| 53 | + let left = 2; |
| 54 | + let right = 5; |
| 55 | + |
| 56 | + let result = true; |
| 57 | + |
| 58 | + assert_eq!(Solution::is_covered(ranges, left, right), result); |
| 59 | + } |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_1893_example_2() { |
| 63 | + let ranges = vec![vec![1, 10], vec![10, 20]]; |
| 64 | + let left = 21; |
| 65 | + let right = 21; |
| 66 | + |
| 67 | + let result = false; |
| 68 | + |
| 69 | + assert_eq!(Solution::is_covered(ranges, left, right), result); |
| 70 | + } |
| 71 | +} |
0 commit comments