DEV Community

Discussion on: How to lose a Job in 10 minutes

 
juropolacko profile image
Juraj Polačko

Can someone please elaborate on why the solution with sorting string literals to be compared and then finding out if they are same (case insensitively) would not be sufficient? How does it not meet the requirements?

I understand that the point of this post is elsewhere but just not to wrap my head around it anymore.

Thank you

Thread Thread
 
fnh profile image
Fabian Holzer

Well, the solution matches the provided test case, but the test suite obviously was not extensive enough to test for all edge cases. Poof provided in his reply the hint

So London and Donlon would go in the same array but not DnnooL

It also was in the "interview" part of the article:

First question, do the letters just ‘rotate’ or they can be randomly mixed up?
Larry (to protect the privacy of the interviewers, I changed their name into a fancy one): Just rotate. First letter goes last

So comparing by the anagram builds up groups of the wrong equivalence class. To use the phrasing of Poofs article, it is "randomly mixing".

But the definition of "just rotate", as I understood it after the new test case, that DnnooL is not in the same equivalence class as London, is to be case insentively the same string as one element of the set that you get when you split the string at any index, swap the parts and concatenate again.

Albeit, I still stand by the general structure of the solution I proposed, which doesn't need reduce at all. Just swap the predicate isAnagram with isRotation, e.g.

function range(n) {
  return Array.from(Array(n).keys());
}

function allRotations(str) {
  return range(str.length)
    .map(index => [str.substring(index), str.substring(0, index)])
    .map(array => array.join("").toLocaleLowerCase());
}

function isRotation(a, b) {
  return allRotations(a).includes(b.toLocaleLowerCase());
}