mediumStringsPattern: Mixed

Interstellar Message Repair Solution

Problem Statement

Given two strings representing encoded messages from a distant planet, determine the minimum number of adjacent character swaps required to make the strings identical. Swaps can only involve characters in alternate positions (i.e., 1st with 2nd, 3rd with 4th, etc.) in either string. If the strings cannot be made identical by swapping only alternate characters, return -1.

Examples

Example 1:
Input:["12435","13254"]
Output:2
Explanation: Swap '1' and '2' in the first string, then swap '3' and '5' to get the second string.
Example 2:
Input:["3142","1234"]
Output:-1
Explanation: The strings cannot be made identical by swapping only adjacent characters in alternate positions.

Constraints

  • 1 <= length of strings <= 100
  • All characters in the strings are unique digits from 0 to 9
Time: O(n) Space: O(n)
The optimized approach would involve using a queue to keep track of the characters that need to be swapped and the positions where they need to be swapped. This would have a time complexity of O(n), which is more efficient.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.