Permutation Difference between Two Strings - Problem

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.

Input & Output

Example 1 — 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 — No Movement
$ Input: s = "ab", t = "ab"
Output: 0
💡 Note: Both strings are identical, so no characters moved positions. All differences are 0.
Example 3 — Complete Reversal
$ Input: s = "abcde", t = "edcba"
Output: 12
💡 Note: Each character moved to the opposite end: 'a' moved 4 positions, 'b' moved 2, 'c' stayed, 'd' moved 2, 'e' moved 4. Total: 4+2+0+2+4 = 12

Constraints

  • 1 ≤ s.length ≤ 26
  • Each character occurs at most once in s
  • t is a permutation of s

Visualization

Tap to expand
Permutation Difference: Sum of position changesString s = "abc"abc012String t = "bac"bac012Character 'a': |0 - 1| = 1Character 'b': |1 - 0| = 1Character 'c': |2 - 2| = 0Total Difference: 1 + 1 + 0 = 2
Understanding the Visualization
1
Input Strings
Two strings s and t where t is a permutation of s
2
Find Differences
For each character, calculate |position_in_s - position_in_t|
3
Sum Total
Add all individual differences to get final result
Key Takeaway
🎯 Key Insight: Use a hash map to store positions from string t for instant O(1) character lookups
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~10 min Avg. Time
342 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