BackmediumStringsAtlassian

Chef's Ingredient Rearrangement Solution

Problem Statement

Given two strings of ingredients, s1 and s2, of the same length, determine the minimum number of swap operations on the characters of s1 to transform it into s2.

Example 1
Input
s1 = 'ab', s2 = 'ba'
Output
1

Explanation: Step-by-step: We need to swap 'a' and 'b' in s1 to get s2. This requires 1 operation.

Example 2
Input
s1 = 'xyz', s2 = 'zyx'
Output
2

Explanation: Step-by-step: We can swap 'x' and 'z' first, then 'y' and 'z' to get s2. This requires 2 operations.

Constraints

  • 1 <= length of s1 == length of s2 <= 100
  • s1 and s2 contain only lowercase English letters
  • The input strings can be modified, and additional space can be used for bookkeeping
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Chef's Ingredient Rearrangement — Problem Statement & Solution Guide

StringsMediumRandom
TimeO(n)
|
SpaceO(1)

Problem Description

Given two strings of ingredients, s1 and s2, of the same length, determine the minimum number of swap operations on the characters of s1 to transform it into s2.

Examples

Example 1

Input

s1 = 'ab', s2 = 'ba'

Output

1

Explanation: Step-by-step: We need to swap 'a' and 'b' in s1 to get s2. This requires 1 operation.

Example 2

Input

s1 = 'xyz', s2 = 'zyx'

Output

2

Explanation: Step-by-step: We can swap 'x' and 'z' first, then 'y' and 'z' to get s2. This requires 2 operations.

Constraints

  • 1 <= length of s1 == length of s2 <= 100
  • s1 and s2 contain only lowercase English letters
  • The input strings can be modified, and additional space can be used for bookkeeping

Optimal Approach & Strategy

An optimized approach is to use a cycle detection algorithm to find the minimum number of swap operations, resulting in a time complexity of O(n).

Brute Force Approach

One possible brute-force approach is to generate all permutations of the first string and count the minimum number of swaps required to transform it into the second string, resulting in a time complexity of O(n!).

Asked in Top Tech Interviews

Atlassian

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.