Skip to content

Commit f48ea8a

Browse files
committed
2364. Count Number of Bad Pairs: AC
1 parent 53a8656 commit f48ea8a

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1790,3 +1790,4 @@ mod s2358_maximum_number_of_groups_entering_a_competition;
17901790
mod s2359_find_closest_node_to_given_two_nodes;
17911791
mod s2360_longest_cycle_in_a_graph;
17921792
mod s2363_merge_similar_items;
1793+
mod s2364_count_number_of_bad_pairs;
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* [2364] Count Number of Bad Pairs
3+
*
4+
* You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].
5+
* Return the total number of bad pairs in nums.
6+
*
7+
* Example 1:
8+
*
9+
* Input: nums = [4,1,3,3]
10+
* Output: 5
11+
* Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
12+
* The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
13+
* The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
14+
* The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
15+
* The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
16+
* There are a total of 5 bad pairs, so we return 5.
17+
*
18+
* Example 2:
19+
*
20+
* Input: nums = [1,2,3,4,5]
21+
* Output: 0
22+
* Explanation: There are no bad pairs.
23+
*
24+
*
25+
* Constraints:
26+
*
27+
* 1 <= nums.length <= 10^5
28+
* 1 <= nums[i] <= 10^9
29+
*
30+
*/
31+
pub struct Solution {}
32+
33+
// problem: https://leetcode.com/problems/count-number-of-bad-pairs/
34+
// discuss: https://leetcode.com/problems/count-number-of-bad-pairs/discuss/?currentPage=1&orderBy=most_votes&query=
35+
36+
// submission codes start here
37+
38+
impl Solution {
39+
pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
40+
nums.into_iter()
41+
.enumerate()
42+
.map(|(i, num)| (i, num - i as i32))
43+
.scan(std::collections::HashMap::new(), |map, (i, num)| {
44+
let same_count = map.entry(num).or_insert(0);
45+
let diff_count = i as i32 - *same_count;
46+
*same_count += 1;
47+
Some(diff_count as i64)
48+
})
49+
.sum()
50+
}
51+
}
52+
53+
// submission codes end
54+
55+
#[cfg(test)]
56+
mod tests {
57+
use super::*;
58+
59+
#[test]
60+
fn test_2364_example_1() {
61+
let nums = vec![4, 1, 3, 3];
62+
63+
let result = 5;
64+
65+
assert_eq!(Solution::count_bad_pairs(nums), result);
66+
}
67+
68+
#[test]
69+
fn test_2364_example_2() {
70+
let nums = vec![1, 2, 3, 4, 5];
71+
72+
let result = 0;
73+
74+
assert_eq!(Solution::count_bad_pairs(nums), result);
75+
}
76+
}

0 commit comments

Comments
 (0)