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 between Two Strings INPUT String s = "abc" a idx: 0 b idx: 1 c idx: 2 String t = "bac" b idx: 0 a idx: 1 c idx: 2 t is a permutation of s Each char appears once s = "abc" t = "bac" ALGORITHM STEPS 1 Build Hash Map Store index of each char in s hashS: a:0, b:1, c:2 2 Build Hash Map for t Store index of each char in t hashT: b:0, a:1, c:2 3 Calculate Differences |hashS[c] - hashT[c]| 4 Sum All Differences |0-1|+|1-0|+|2-2| = 1 + 1 + 0 = 2 FINAL RESULT Character Position Differences: Char s idx t idx Diff a 0 1 1 b 1 0 1 c 2 2 0 Total = 1 + 1 + 0 Output: 2 OK - Result Verified Permutation difference = 2 Key Insight: Using hash maps allows O(1) lookup for character positions in both strings. Time Complexity: O(n) where n is string length. Space Complexity: O(n) for the hash maps. TutorialsPoint - Permutation Difference between Two Strings | Hash Approach
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