Skip to content

Commit

Permalink
Add problem 1879: Minimum XOR Sum of Two Arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed May 4, 2024
1 parent 23f52c9 commit 947cd3e
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 @@ -1397,6 +1397,7 @@ pub mod problem_1871_jump_game_vii;
pub mod problem_1872_stone_game_viii;
pub mod problem_1876_substrings_of_size_three_with_distinct_characters;
pub mod problem_1877_minimize_maximum_pair_sum_in_array;
pub mod problem_1879_minimum_xor_sum_of_two_arrays;
pub mod problem_1880_check_if_word_equals_summation_of_two_words;
pub mod problem_1881_maximum_value_after_insertion;
pub mod problem_1884_egg_drop_with_2_eggs_and_n_floors;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
pub struct Solution;

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

impl Solution {
pub fn minimum_xor_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
assert_eq!(nums1.len(), nums2.len());

let n = nums1.len();
let mut cache = vec![0_u32; 1 << n].into_boxed_slice();

for selection in 1_usize..cache.len() {
let bottom_num = nums2[(selection.count_ones() - 1) as usize];
let mut value = u32::MAX;
let mut remaining_bits = selection;

loop {
let top_index = remaining_bits.trailing_zeros();
let probe = 1 << top_index;

value = value.min(cache[selection ^ probe] + (nums1[top_index as usize] ^ bottom_num) as u32);

remaining_bits ^= probe;

if remaining_bits == 0 {
break;
}
}

cache[selection] = value;
}

cache.last().copied().unwrap() as _
}
}

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

impl super::Solution for Solution {
fn minimum_xor_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
Self::minimum_xor_sum(nums1, nums2)
}
}

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

pub trait Solution {
fn minimum_xor_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i32;
}

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

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

for ((nums1, nums2), expected) in test_cases {
assert_eq!(S::minimum_xor_sum(nums1.to_vec(), nums2.to_vec()), expected);
}
}
}

0 comments on commit 947cd3e

Please sign in to comment.