Skip to content

Commit

Permalink
Added remove k digits solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Nov 14, 2024
1 parent 685e214 commit 6f87c1b
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ programming challenges completed in other languages.
- Most Beautiful Item for Each Query (https://leetcode.com/problems/most-beautiful-item-for-each-query)
- Count Number of Fair Pairs(https://leetcode.com/problems/count-the-number-of-fair-pairs)
- Sum of Square Numbers (https://leetcode.com/problems/sum-of-square-numbers)
_ Minimized Maximum of Products Distributed to Any Store (https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store)
- Minimized Maximum of Products Distributed to Any Store (https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store)
- Remove K Digits (https://leetcode.com/problems/remove-k-digits)

#### Hard

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,4 @@ mod max_beauty;
mod count_fair_pairs;
mod square_numbers;
mod minimized_maximum;
mod remove_k_digits;
46 changes: 46 additions & 0 deletions src/leetcode/remove_k_digits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub fn remove_kdigits(number: String, k: i32) -> String {
let mut k = k as usize;
let mut stack = String::with_capacity(number.len() - k);
for digit in number.chars() {
while k > 0 && !stack.is_empty() && digit < stack.chars().last().unwrap() {
// Remove digits larger than the current one.
stack.pop();
k -= 1;
}
if stack.is_empty() && digit == '0' {
// Skip leading zeros.
continue;
}
stack.push(digit);
}

// Remove any remaining right digits if not all digits were removed in the main loop.
for _ in 0..k {
stack.pop();
}

match stack.is_empty() {
true => "0".to_string(),
false => stack,
}
}

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

#[test]
fn removes_k_digits_to_achieve_smallest_number_possible() {
assert_eq!("1219".to_string(), remove_kdigits("1432219".to_string(), 3))
}

#[test]
fn digits_with_trailing_zeros() {
assert_eq!("200".to_string(), remove_kdigits("10200".to_string(), 1))
}

#[test]
fn remove_all_digits() {
assert_eq!("0".to_string(), remove_kdigits("10".to_string(), 2))
}
}

0 comments on commit 6f87c1b

Please sign in to comment.