Problem Description
Given two strings s and t, where every character in s is unique and t is a permutation of s, calculate the permutation difference. The permutation difference is defined as the sum of the absolute differences between the indices of each character in s and its corresponding index in t.
Key Insights
- Since s contains unique characters, we can easily map each character to its index.
- Create a hash map (or dictionary) for one of the strings (e.g., s) for constant time lookups.
- Iterate over the characters, find their positions in s and t, and sum the absolute differences of these positions.
- The constraints guarantee small input size (max 26 characters), so simplicity in design is acceptable.
Space and Time Complexity
Time Complexity: O(n) where n is the length of string s (or t). Space Complexity: O(n) for storing the index mapping.
Solution
We map each character in s to its index using a hash table (or dictionary). Then, we iterate over each character in t, lookup its index from the mapping, and compute the absolute difference between this index and the current index in t. Summing these absolute differences gives us the required permutation difference.