Skip to content

Commit fcd5222

Browse files
committed
Add problem 3137: Minimum Number of Operations to Make Word K-Periodic
1 parent 08c807e commit fcd5222

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,6 +2101,7 @@ pub mod problem_3127_make_a_square_with_the_same_color;
21012101
pub mod problem_3131_find_the_integer_added_to_array_i;
21022102
pub mod problem_3133_minimum_array_end;
21032103
pub mod problem_3136_valid_word;
2104+
pub mod problem_3137_minimum_number_of_operations_to_make_word_k_periodic;
21042105
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21052106

21062107
#[cfg(test)]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::collections::HashMap;
6+
use std::collections::hash_map::Entry;
7+
use std::num::NonZeroUsize;
8+
9+
impl Solution {
10+
pub fn minimum_operations_to_make_k_periodic(word: String, k: i32) -> i32 {
11+
let k = NonZeroUsize::new(k.cast_unsigned() as _).unwrap();
12+
let mut counts = HashMap::<_, u32>::new();
13+
14+
word.as_bytes()
15+
.chunks_exact(k.get())
16+
.for_each(|chunk| match counts.entry(chunk) {
17+
Entry::Occupied(occupied_entry) => *occupied_entry.into_mut() += 1,
18+
Entry::Vacant(vacant_entry) => {
19+
vacant_entry.insert(1);
20+
}
21+
});
22+
23+
((word.len() / k) as u32 - counts.values().copied().fold(0, u32::max)).cast_signed()
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn minimum_operations_to_make_k_periodic(word: String, k: i32) -> i32 {
31+
Self::minimum_operations_to_make_k_periodic(word, k)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod hash_map;
2+
3+
pub trait Solution {
4+
fn minimum_operations_to_make_k_periodic(word: String, k: i32) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(("leetcodeleet", 4), 1), (("leetcoleet", 2), 3)];
13+
14+
for ((word, k), expected) in test_cases {
15+
assert_eq!(S::minimum_operations_to_make_k_periodic(word.to_string(), k), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)