DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #268 - Swapping Characters in Strings

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 (3)

Collapse
 
dry profile image
Hayden Mankin • Edited

Javascript 1 liners

Recursive

const obtain=(s,t,count=0)=>s?~(idx=t.indexOf(s[0]))?obtain(s.slice(1),t.slice(0,idx)+t.slice(idx+1),idx+count):-1:count;

console.log(obtain('abcdef', 'abdfec'));  // 4
console.log(obtain('abcd', 'accd'));      // -1
console.log(obtain('ab', 'ab'));          // 0
console.log(obtain('ab', 'ba'));          // 1
console.log(obtain('aaa', 'aaa'));        // 0

Iterative

const obtain = (s,t)=>s.split("").reduce((a,v)=>~a&&~(i=t.indexOf(v))?~~(t=t.slice(0,i)+t.slice(i+1))||a+i:-1,0)

console.log(obtain('abcdef', 'abdfec'));  // 4
console.log(obtain('abcd', 'accd'));      // -1
console.log(obtain('ab', 'ab'));          // 0
console.log(obtain('ab', 'ba'));          // 1
console.log(obtain('aaa', 'aaa'));        // 0
Collapse
 
djjensen profile image
David Jensen

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