#3146

Permutation Difference between Two Strings

Easy
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we will use a single pass to create a mapping of indices for both strings. This allows us to calculate the differences in a more efficient manner, reducing the time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a dictionary to store the indices of characters in string 's'.
  2. 2Step 2: Iterate through string 't' and for each character, find its index in the dictionary for 's'.
  3. 3Step 3: Calculate the absolute difference of the indices and accumulate it.
  4. 4Step 4: Return the accumulated difference.
solution.py11 lines
1# Full working Python code
2
3def permutation_difference(s, t):
4    index_map = {char: i for i, char in enumerate(s)}
5    difference = 0
6    for i, char in enumerate(t):
7        difference += abs(index_map[char] - i)
8    return difference
9
10# Example usage
11print(permutation_difference('abc', 'bac'))  # Output: 2

Complexity note: The time complexity is O(n) because we make a single pass to create the index map and another pass to calculate the differences. The space complexity is O(n) due to the storage of the index map.

  • 1Using a mapping of indices allows for efficient lookups and calculations.
  • 2Understanding the problem constraints (unique characters) simplifies the approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.