#2287
Easy Algorithms Rearrange characters to make target string
Hash Table String Counting
61.1% acceptance
Feb 25, 2026
525
38
You are given two 0-indexed strings s and target. You want to create copies of target by taking letters from s and rearranging them.
Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn rearrange_characters(s: String, target: String) -> i32 {
let mut s_count = [0i32; 26];
let mut t_count = [0i32; 26];
for b in s.bytes() { s_count[(b - b'a') as usize] += 1; }
for b in target.bytes() { t_count[(b - b'a') as usize] += 1; }
let mut result = i32::MAX;
for i in 0..26 {
if t_count[i] > 0 {
result = result.min(s_count[i] / t_count[i]);
}
}
if result == i32::MAX { 0 } else { result }
}
}