#3146
Easy Algorithms Permutation difference between two strings
Hash Table String
87.8% acceptance
Feb 24, 2026
190
17
You are given two strings s and t such that every character occurs at most once in s
and t is a permutation of s.
The permutation difference between s and t is defined as the sum of the absolute
difference between the index of the occurrence of each character in s and the index
of the occurrence of the same character in t.
Return the permutation difference between s and t.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn find_permutation_difference(s: String, t: String) -> i32 {
let mut pos_s = [0i32; 26];
let mut pos_t = [0i32; 26];
for (i, &b) in s.as_bytes().iter().enumerate() {
pos_s[(b - b'a') as usize] = i as i32;
}
for (i, &b) in t.as_bytes().iter().enumerate() {
pos_t[(b - b'a') as usize] = i as i32;
}
s.as_bytes()
.iter()
.map(|&b| (pos_s[(b - b'a') as usize] - pos_t[(b - b'a') as usize]).abs())
.sum()
}
}