Skip to content

Commit

Permalink
Add problem 2053: Kth Distinct String in an Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 5, 2024
1 parent a082f37 commit d428449
Show file tree
Hide file tree
Showing 3 changed files with 62 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 @@ -1408,6 +1408,7 @@ pub mod problem_2038_remove_colored_pieces_if_both_neighbors_are_the_same_color;
pub mod problem_2042_check_if_numbers_are_ascending_in_a_sentence;
pub mod problem_2043_simple_bank_system;
pub mod problem_2047_number_of_valid_words_in_a_sentence;
pub mod problem_2053_kth_distinct_string_in_an_array;

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

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

use std::collections::HashMap;

impl Solution {
pub fn kth_distinct(arr: Vec<String>, k: i32) -> String {
let mut counts = HashMap::<_, u16>::new();

for s in &arr {
counts.entry(s.as_str()).and_modify(|count| *count += 1).or_insert(1);
}

arr.iter()
.filter(|&s| counts[s.as_str()] == 1)
.nth(k as u32 as usize - 1)
.map_or_else(String::new, String::clone)
}
}

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

impl super::Solution for Solution {
fn kth_distinct(arr: Vec<String>, k: i32) -> String {
Self::kth_distinct(arr, k)
}
}

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

pub trait Solution {
fn kth_distinct(arr: Vec<String>, k: i32) -> String;
}

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

pub fn run<S: Solution>() {
let test_cases = [
((&["d", "b", "c", "b", "c", "a"] as &[_], 2), "a"),
((&["aaa", "aa", "a"], 1), "aaa"),
((&["a", "b", "a"], 3), ""),
];

for ((arr, k), expected) in test_cases {
assert_eq!(
S::kth_distinct(arr.iter().copied().map(str::to_string).collect(), k),
expected,
);
}
}
}

0 comments on commit d428449

Please sign in to comment.