Show problems as
Classic problem #854HardHash TableStringBreadth-First Search

K-Similar Strings

Real-world version: Fewest Swaps Between Two Blend Codes
Tracked in this browser only
Read K-Similar Strings on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Two blend codes s1 and s2 are the same length and use only the letters 'a' through 'f'. They are rearrangements of each other, so each letter appears the same number of times in both.

One swap exchanges the letters at two positions of s1. Return the fewest swaps that turn s1 into s2.

Examples

Example 1

Input
s1 = "abcd", s2 = "badc"
Output
2

Swapping the first two letters gives "bacd", and swapping the last two gives "badc".

Example 2

Input
s1 = "abc", s2 = "bca"
Output
2

Swapping the first two letters gives "bac", and swapping the last two gives "bca".

Example 3

Input
s1 = "abcdef", s2 = "abcdef"
Output
0

The two codes already read the same, so no swap is needed.

Constraints

  • 1 <= s1.length <= 20
  • s1.length == s2.length
  • s1 and s2 use only the letters a, b, c, d, e and f
  • s2 is a rearrangement of s1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def fewest_code_swaps(s1: str, s2: str) -> int:
Java
public int fewestCodeSwaps(String s1, String s2)