You are given two strings s
and t
. Both strings have length n
and consist of lowercase letters.
You can swap any two adjacent characters of s
any number of times.
Output the minimum number of moves to transform s to t. If it is impossible to obtain the string t
using moves, return -1.
Examples
('abcdef', 'abdfec') => 4
('abcd', 'accd') => -1
('ab', 'ab') => 0
('ab', 'ba') => 1
('aaa', 'aaa') => 0
Tests
{s:'abcdef', t:'abdfec'}
{s:'abcd', t:'accd'}
{s:'ab', t:'ab'}
{s:'ab', t:'ba'}
{s:'aaa', t:'aaa'}
Good luck!
This challenge comes from arhigod on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (2)
Javascript 1 liners
Recursive
Iterative
I see similar answers but I put in the work so I thought I'd post.
Javascript:
var numSwapsToEquality = (str1, str2) => { const chars1 = str1.split(""); const chars2 = str2.split(""); return chars1.slice().sort().join("") !== chars2.slice().sort().join("") ? -1 : chars2.reduce((countTotal, char2) => { const count = -( chars1.reduce( (c, char1) => (c < 1 ? c : char1 !== char2 ? c + 1 : -c), 1 ) + 1 ); chars1.splice(count, 1); return countTotal + count; }, 0); }; console.log(numSwapsToEquality('abcdef', 'abdfec')); // 4 console.log(numSwapsToEquality('abcd', 'accd')); // -1 console.log(numSwapsToEquality('ab', 'ab')); // 0 console.log(numSwapsToEquality('ab', 'ba')); // 1 console.log(numSwapsToEquality('aaa', 'aaa')); // 0