Problem · String

Minimum Adjacent Transpositions

Learn this problem
MediumEpic logoEpicFULLTIMEOA

Problem statement

source and target contain the same ASCII characters with the same frequencies.

In one operation, swap two adjacent characters in source. Return the minimum number of operations required to transform source into target.

Function

minimumAdjacentSwaps(source: String, target: String) → long

Examples

Example 1

source = "GUM"target = "MUG"return = 3

Moving M to the front takes two swaps, then moving U ahead of G takes one more.

Example 2

source = "aabb"target = "bbaa"return = 4

Each of the two b characters crosses both a characters.

Constraints

  • 1 <= source.length == target.length <= 200000
  • Both strings contain the same ASCII characters with the same frequencies.

More Epic problems

drafts saved locally
public long minimumAdjacentSwaps(String source, String target) {
    // Write your code here.
}
source"GUM"
target"MUG"
expected3
checking account