Minimum Adjacent Swaps — Problem Statement & Solution Guide
Problem Description
Given two strings, original and corrupted, where corrupted is a subsequence of original, determine the minimum number of adjacent character swaps required to transform corrupted into a subsequence of original in-place.
Examples
Input
original = 'abcde', corrupted = 'bdca'
Output
1
Explanation: Step-by-step: 1. Find the first occurrence of 'b' in 'original' at index 1. 2. Find the first occurrence of 'd' in 'original' at index 3. 3. Swap 'd' with 'e' at index 3 to get 'bdca'.
Input
original = 'abcde', corrupted = 'acdb'
Output
1
Explanation: Step-by-step: 1. Find the first occurrence of 'a' in 'original' at index 0. 2. Find the first occurrence of 'c' in 'original' at index 2. 3. Swap 'c' with 'd' at index 2 to get 'acdb'.
Constraints
- 1 <= length of transmission string <= 1000
- 1 <= length of subsequence <= 100
Optimal Approach & Strategy
The optimized approach involves using a two-pointer technique to compare the subsequence with the transmission string and identify the characters that need to be swapped. This approach has a time complexity of O(n), where n is the length of the transmission string. It also uses a greedy strategy to minimize the number of swaps required.
Brute Force Approach
The brute-force approach would involve generating all possible permutations of the subsequence and counting the number of swaps required to transform each permutation into the correct subsequence. This approach has a time complexity of O(n!), which is inefficient for large inputs. It would also require comparing each permutation with the original transmission string to determine the correct swaps.
Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.