#3039
Medium Algorithms Apply operations to make string empty
Array Hash Table Sorting Counting
57.4% acceptance
Feb 25, 2026
167
8
You are given a string s.
Consider performing the following operation until s becomes empty:
For every alphabet character from 'a' to 'z', remove the first occurrence of that character in s (if it exists).
Return the value of the string s right before applying the last operation.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn last_non_empty_string(s: String) -> String {
let mut freq = [0u32; 26];
for b in s.bytes() { freq[(b-b'a') as usize] += 1; }
let max_f = *freq.iter().max().unwrap();
// Characters that appear max_f times
let _chars_in_last: Vec<u8> = (0..26u8).filter(|&c| freq[c as usize] == max_f).collect();
// In the last operation, the last occurrence of each such char is the result
let mut result: Vec<u8> = Vec::new();
let mut seen = [false; 26];
for b in s.bytes().rev() {
let c = (b - b'a') as usize;
if freq[c] == max_f && !seen[c] {
seen[c] = true;
result.push(b);
}
}
result.reverse();
String::from_utf8(result).unwrap()
}
}