Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Minimum Swaps to Match Strings

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Minimum Swaps to Match Strings. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

A PhonePe mobile flow receives two representations of the same token with characters in different positions. Given two strings, compute the minimum number of arbitrary swaps of characters in the first string required to transform it into the second.

A swap may exchange characters at any two positions. Return -1 if the strings cannot be made equal. To make the mapping unambiguous, every character appears at most once in each string.

Formal Specification

Implement minimum_swaps(source, target):

  • Input: Two strings source and target containing distinct lowercase English letters.
  • Output: An integer representing the minimum number of arbitrary swaps needed, or -1 if transformation is impossible.
  • The strings are considered equal only when their characters match at every position.

Constraints

  • 1 <= len(source), len(target) <= 10^5
  • Both strings contain only lowercase English letters
  • Each character appears at most once in each string
  • A valid transformation requires equal lengths and equal character sets

Function Signature

def minimum_swaps(source, target):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output