Skip to content

Commit

Permalink
Add problem 1850: Minimum Adjacent Swaps to Reach the Kth Smallest Nu…
Browse files Browse the repository at this point in the history
…mber
  • Loading branch information
EFanZh committed Aug 2, 2024
1 parent 5168539 commit 5a651e8
Show file tree
Hide file tree
Showing 3 changed files with 78 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 @@ -1380,6 +1380,7 @@ pub mod problem_1846_maximum_element_after_decreasing_and_rearranging;
pub mod problem_1847_closest_room;
pub mod problem_1848_minimum_distance_to_the_target_element;
pub mod problem_1849_splitting_a_string_into_descending_consecutive_values;
pub mod problem_1850_minimum_adjacent_swaps_to_reach_the_kth_smallest_number;
pub mod problem_1851_minimum_interval_to_include_each_query;
pub mod problem_1854_maximum_population_year;
pub mod problem_1855_maximum_distance_between_a_pair_of_values;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
pub struct Solution;

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

impl Solution {
pub fn get_min_swaps(num: String, k: i32) -> i32 {
let mut num = num.into_bytes();
let mut target_num = num.clone();
let k = k as u32;
let mut result = 0;

for _ in 0..k {
let mut i = target_num.len();
let mut prev = 0;

for &x in target_num.iter().rev() {
i -= 1;

let found = x < prev;

prev = x;

if found {
break;
}
}

let j = i + 1 + target_num[i + 2..].partition_point(|&x| x > prev);

target_num.swap(i, j);
target_num[i + 1..].reverse();
}

for (i, &target) in target_num.iter().enumerate() {
let j = num[i..].iter().position(|&c| c == target).unwrap();

result += j;
num[i..i + 1 + j].rotate_right(1);
}

result as _
}
}

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

impl super::Solution for Solution {
fn get_min_swaps(num: String, k: i32) -> i32 {
Self::get_min_swaps(num, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod brute_force;

pub trait Solution {
fn get_min_swaps(num: String, k: i32) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [(("5489355142", 4), 2), (("11112", 4), 4), (("00123", 1), 1)];

for ((num, k), expected) in test_cases {
assert_eq!(S::get_min_swaps(num.to_string(), k), expected);
}
}
}

0 comments on commit 5a651e8

Please sign in to comment.