Skip to content

Commit f16d348

Browse files
committed
Add problem 2965: Find Missing and Repeated Values
1 parent 61800b9 commit f16d348

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2031,6 +2031,7 @@ pub mod problem_2958_length_of_longest_subarray_with_at_most_k_frequency;
20312031
pub mod problem_2960_count_tested_devices_after_test_operations;
20322032
pub mod problem_2961_double_modular_exponentiation;
20332033
pub mod problem_2962_count_subarrays_where_max_element_appears_at_least_k_times;
2034+
pub mod problem_2965_find_missing_and_repeated_values;
20342035

20352036
#[cfg(test)]
20362037
mod test_utilities;
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn find_missing_and_repeated_values(grid: Vec<Vec<i32>>) -> Vec<i32> {
7+
let n = (grid.len() as u32).pow(2);
8+
let mut sum = 0;
9+
let mut square_sum = 0;
10+
11+
grid.into_iter().flatten().for_each(|value| {
12+
sum += value;
13+
square_sum += i64::from(value.cast_unsigned().pow(2));
14+
});
15+
16+
let expected_sum = n * (1 + n) / 2;
17+
18+
let expected_square_sum = {
19+
let n = u64::from(n);
20+
21+
n * (1 + n) * (2 * n + 1) / 6
22+
};
23+
24+
let a_minus_b = sum - expected_sum.cast_signed();
25+
let a_squared_minus_b_squared = (square_sum - expected_square_sum.cast_signed()) as i32;
26+
let a_plus_b = a_squared_minus_b_squared / a_minus_b;
27+
let a = (a_minus_b + a_plus_b) >> 1;
28+
let b = a_plus_b - a;
29+
30+
vec![a, b]
31+
}
32+
}
33+
34+
// ------------------------------------------------------ snip ------------------------------------------------------ //
35+
36+
impl super::Solution for Solution {
37+
fn find_missing_and_repeated_values(grid: Vec<Vec<i32>>) -> Vec<i32> {
38+
Self::find_missing_and_repeated_values(grid)
39+
}
40+
}
41+
42+
#[cfg(test)]
43+
mod tests {
44+
#[test]
45+
fn test_solution() {
46+
super::super::tests::run::<super::Solution>();
47+
}
48+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod mathematical;
2+
3+
pub trait Solution {
4+
fn find_missing_and_repeated_values(grid: Vec<Vec<i32>>) -> Vec<i32>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
use crate::test_utilities::Matrix;
11+
12+
pub fn run<S: Solution>() {
13+
let test_cases = [
14+
(&[[1, 3], [2, 2]] as &dyn Matrix<_>, [2, 4]),
15+
(&[[9, 1, 7], [8, 9, 2], [3, 4, 6]], [9, 5]),
16+
];
17+
18+
for (grid, expected) in test_cases {
19+
assert_eq!(S::find_missing_and_repeated_values(grid.to_vec()), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)