algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
2 shown · 0/261 solved

Minimum Adjacent Swaps to Transform

SilverCommunity Beta
Asked atEpic Systems
Solve problem →
2000ms256MBAdded Aug 31, 2026

You are given two strings source and target of the same length. target is guaranteed to be a permutation of source: both strings contain the same characters with the same frequencies.

In one operation you may swap two adjacent characters of source.

Return the minimum number of operations required to transform source into target.

Note that the answer can exceed the 32-bit integer range.

Examples

Example 1

Input: source = "GUM", target = "MUG"
Output: 3
Explanation: One optimal sequence is "GUM" -> "GMU" (swap positions 1 and 2) -> "MGU" (swap positions 0 and 1) -> "MUG" (swap positions 1 and 2). No sequence of fewer than 3 adjacent swaps works.

Example 2

Input: source = "ABAB", target = "BABA"
Output: 2
Explanation: "ABAB" -> "BAAB" (swap positions 0 and 1) -> "BABA" (swap positions 2 and 3). With duplicate letters, matching each occurrence to the nearest available occurrence in target keeps the swap count at 2.

Constraints

  • 1≤1 \leq1≤ source.length ≤105\leq 10^5≤105
  • target.length === source.length
  • source and target consist of uppercase English letters
  • target is a permutation of source

Details

Solved by3 people
Time limit2000ms
Memory256MB
AddedAug 31, 202611 days ago