Permutation Difference between Two Strings - Problem
Imagine you have two strings where one is a rearranged version of the other. Your task is to measure how much the characters have "moved" from their original positions.
Given two strings s and t where:
- Every character appears exactly once in each string
tis a permutation (rearrangement) ofs
The permutation difference is calculated as: the sum of absolute differences between the index positions of each character in both strings.
Example: If s = "abc" and t = "bac", then:
- Character 'a': position 0 in s, position 1 in t → |0-1| = 1
- Character 'b': position 1 in s, position 0 in t → |1-0| = 1
- Character 'c': position 2 in s, position 2 in t → |2-2| = 0
- Total difference: 1 + 1 + 0 = 2
Return the permutation difference between the two strings.
Input & Output
example_1.py — Basic Case
$
Input:
s = "abc", t = "bac"
›
Output:
2
💡 Note:
Character 'a': position 0 in s, position 1 in t → |0-1| = 1. Character 'b': position 1 in s, position 0 in t → |1-0| = 1. Character 'c': position 2 in s, position 2 in t → |2-2| = 0. Total: 1 + 1 + 0 = 2.
example_2.py — No Movement
$
Input:
s = "abcde", t = "abcde"
›
Output:
0
💡 Note:
All characters are in the same positions in both strings, so all differences are 0. Total: 0 + 0 + 0 + 0 + 0 = 0.
example_3.py — Complete Reversal
$
Input:
s = "abc", t = "cba"
›
Output:
4
💡 Note:
Character 'a': position 0 in s, position 2 in t → |0-2| = 2. Character 'b': position 1 in s, position 1 in t → |1-1| = 0. Character 'c': position 2 in s, position 0 in t → |2-0| = 2. Total: 2 + 0 + 2 = 4.
Constraints
- 1 ≤ s.length ≤ 1000
- t.length == s.length
- s and t consist of lowercase English letters
- Each character appears at most once in s
- t is a permutation of s
Visualization
Tap to expand
Understanding the Visualization
1
Record Home Addresses
Create a hash map storing each character's original position in string s
2
Check Party Locations
For each character in string t, look up their home position
3
Calculate Travel Distance
Compute absolute difference between home and party positions
4
Sum Total Movement
Add up all individual distances to get total permutation difference
Key Takeaway
🎯 Key Insight: By storing character positions in a hash map, we transform expensive O(n) searches into instant O(1) lookups, reducing overall complexity from O(n²) to O(n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code