Skip to content

Commit f4fd49f

Browse files
committed
Add problem 3152: Special Array II
1 parent 4e591b5 commit f4fd49f

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2109,6 +2109,7 @@ pub mod problem_3146_permutation_difference_between_two_strings;
21092109
pub mod problem_3147_taking_maximum_energy_from_the_mystic_dungeon;
21102110
pub mod problem_3148_maximum_difference_score_in_a_grid;
21112111
pub mod problem_3151_special_array_i;
2112+
pub mod problem_3152_special_array_ii;
21122113
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21132114

21142115
#[cfg(test)]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
pub mod prefix_sums;
2+
3+
pub trait Solution {
4+
fn is_array_special(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<bool>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
((&[3, 4, 1, 2, 6] as &[_], &[[0, 4]] as &[_]), &[false] as &[_]),
14+
((&[4, 3, 1, 6], &[[0, 2], [2, 3]]), &[false, true]),
15+
];
16+
17+
for ((nums, queries), expected) in test_cases {
18+
assert_eq!(
19+
S::is_array_special(nums.to_vec(), queries.iter().map(Vec::from).collect()),
20+
expected,
21+
);
22+
}
23+
}
24+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::mem;
6+
7+
impl Solution {
8+
pub fn is_array_special(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<bool> {
9+
let mut nums = nums.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
10+
let mut iter = nums.iter_mut();
11+
let mut sum = 0;
12+
let mut prev = mem::take(iter.next().unwrap());
13+
14+
iter.for_each(|num| {
15+
sum += !(prev ^ *num) & 1;
16+
prev = mem::replace(num, sum);
17+
});
18+
19+
queries
20+
.into_iter()
21+
.map(|query| {
22+
let [from, to] = query.try_into().ok().unwrap();
23+
24+
nums[to.cast_unsigned() as usize] == nums[from.cast_unsigned() as usize]
25+
})
26+
.collect()
27+
}
28+
}
29+
30+
// ------------------------------------------------------ snip ------------------------------------------------------ //
31+
32+
impl super::Solution for Solution {
33+
fn is_array_special(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<bool> {
34+
Self::is_array_special(nums, queries)
35+
}
36+
}
37+
38+
#[cfg(test)]
39+
mod tests {
40+
#[test]
41+
fn test_solution() {
42+
super::super::tests::run::<super::Solution>();
43+
}
44+
}

0 commit comments

Comments
 (0)