Skip to main content

K-Similar Strings

Problem statement

Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.

Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.

Example 1:

Input: s1 = "ab", s2 = "ba"Output: 1

Example 2:

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

Constraints:

  • 1 <= s1.length <= 20
  • s2.length == s1.length
  • s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
  • s2 is an anagram of s1.

My solution

/**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var kSimilarity = function(s1, s2) {
if (s1 === s2) {
return 0
}

const queue = [s1]
const visited = new Set([s1])
let steps = 0;


while (queue.length) {
const size = queue.length;

for (let i = 0; i < size; i++) {
const currStr = queue.shift();

if (currStr === s2) {
return steps;
}

const nextStrs = getNextStr(currStr, s2)
for (const next of nextStrs) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next)
}
}
}

steps++
}
return steps
};

function getNextStr(s1, s2) {
const nextStrs = [];
let i = 0;

while (i < s1.length) {
if (s1.charAt(i) !== s2.charAt(i)) {
break;
}
i++;
}

for (let j = i + 1; j < s1.length; j++) {
if (s1.charAt(j) === s2.charAt(i)) {
nextStrs.push(swap(s1, i, j))
}
}
return nextStrs
}

function swap(str, i, j) {
let arr = str.split("");
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr.join("");
}