Skip to content

Commit

Permalink
Add problem 1718: Construct the Lexicographically Largest Valid Sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 20, 2023
1 parent c3c8c44 commit a7f2961
Show file tree
Hide file tree
Showing 3 changed files with 92 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 @@ -1276,6 +1276,7 @@ pub mod problem_1711_count_good_meals;
pub mod problem_1712_ways_to_split_array_into_three_subarrays;
pub mod problem_1716_calculate_money_in_leetcode_bank;
pub mod problem_1717_maximum_score_from_removing_substrings;
pub mod problem_1718_construct_the_lexicographically_largest_valid_sequence;
pub mod problem_1720_decode_xored_array;
pub mod problem_1721_swapping_nodes_in_a_linked_list;
pub mod problem_1725_number_of_rectangles_that_can_form_the_largest_square;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
pub struct Solution;

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

impl Solution {
fn helper(buffer: &mut [i32], available: u32) -> bool {
buffer.split_first_mut().map_or(true, |(first, rest)| {
if *first == 0 {
let mut bits = available;

while bits != 0 {
let candidate = 32 - bits.trailing_zeros();
let bit = 1 << bits.trailing_zeros();

if candidate == 1 {
*first = candidate as _;

if Self::helper(rest, available ^ bit) {
return true;
}

*first = 0;
} else {
let other_index = candidate as usize - 1;

if rest.get(other_index).copied() == Some(0) {
*first = candidate as _;
rest[other_index] = candidate as _;

if Self::helper(rest, available ^ bit) {
return true;
}

*first = 0;
rest[other_index] = 0;
}
}

bits ^= bit;
}

false
} else {
Self::helper(rest, available)
}
})
}

pub fn construct_distanced_sequence(n: i32) -> Vec<i32> {
let n = n as u32;
let mut result = vec![0; n as usize * 2 - 1];

Self::helper(&mut result, u32::MAX << (32 - n));

result
}
}

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

impl super::Solution for Solution {
fn construct_distanced_sequence(n: i32) -> Vec<i32> {
Self::construct_distanced_sequence(n)
}
}

#[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 iterative;

pub trait Solution {
fn construct_distanced_sequence(n: i32) -> Vec<i32>;
}

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

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

for (n, expected) in test_cases {
assert_eq!(S::construct_distanced_sequence(n), expected);
}
}
}

0 comments on commit a7f2961

Please sign in to comment.