Skip to content

Commit

Permalink
Add problem 2364: Count Number of Bad Pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 16, 2024
1 parent 8aed493 commit 96d6b41
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,7 @@ pub mod problem_2357_make_array_zero_by_subtracting_equal_amounts;
pub mod problem_2358_maximum_number_of_groups_entering_a_competition;
pub mod problem_2360_longest_cycle_in_a_graph;
pub mod problem_2363_merge_similar_items;
pub mod problem_2364_count_number_of_bad_pairs;

#[cfg(test)]
mod test_utilities;
51 changes: 51 additions & 0 deletions src/problem_2364_count_number_of_bad_pairs/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::collections::hash_map::Entry;
use std::collections::HashMap;

impl Solution {
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
let n = nums.len();
let mut counts = HashMap::new();
let mut good_pairs = 0;

(0..).zip(nums).for_each(|(i, num)| {
let key = num - i;

match counts.entry(key) {
Entry::Occupied(occupied_entry) => {
let count = occupied_entry.into_mut();

good_pairs += *count;

*count += 1;
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(1);
}
}
});

let n = n as u64;

(n * (n - 1) / 2 - good_pairs) as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_bad_pairs(nums: Vec<i32>) -> i64 {
Self::count_bad_pairs(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2364_count_number_of_bad_pairs/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn count_bad_pairs(nums: Vec<i32>) -> i64;
}

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

pub fn run<S: Solution>() {
let test_cases = [(&[4, 1, 3, 3] as &[_], 5), (&[1, 2, 3, 4, 5], 0)];

for (nums, expected) in test_cases {
assert_eq!(S::count_bad_pairs(nums.to_vec()), expected);
}
}
}

0 comments on commit 96d6b41

Please sign in to comment.