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
  • t is a permutation (rearrangement) of s

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
Character Movement VisualizationOriginal String (s)apos: 0bpos: 1cpos: 2Rearranged String (t)bpos: 0apos: 1cpos: 2moved 1moved 1no moveMovement CalculationCharacter 'a': |0 - 1| = 1Character 'b': |1 - 0| = 1Character 'c': |2 - 2| = 0Total Difference: 2💡 Hash table enables O(1) position lookups!
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).
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
28.4K Views
Medium Frequency
~12 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen