Given an array of equal-length strings, you'd like to know if it's possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. Return true if it's possible, and false if not.
Note: You're only rearranging the order of the strings, not the order of the letters within the strings!
Example
For inputArray = ["aba", "bbb", "bab"], the output should be:
solution(inputArray) = false.
There are 6 possible arrangements for these strings:
* ["aba", "bbb", "bab"]
* ["aba", "bab", "bbb"]
* ["bbb", "aba", "bab"]
* ["bbb", "bab", "aba"]
* ["bab", "bbb", "aba"]
* ["bab", "aba", "bbb"]
None of these satisfy the condition of consecutive strings differing by 1 character, so the answer is false.
For inputArray = ["ab", "bb", "aa"], the output should be:
solution(inputArray) = true.
It's possible to arrange these strings in a way that each consecutive pair of strings differ by 1 character (eg: "aa", "ab", "bb" or "bb", "ab", "aa"), so return true.
I think that the algorithm could be described as follows
Write a function which counts the differences between two strings (difCount())
Compare every pair of strings (i.e., 1 with 2, 1 with 3, 2 with 3) to check that all strings has a "friend" which differs only by 1 char.
If there's at least one string that hasn't got a pair, the test fails.
arr = ["ff", "gf", "af", "ar", "hf"];
// count how many letters are differnt between two strings
function difCount(str1, str2){
dif_count = 0;
[...str1].map((val, ind) => {
// val != str2[ind] is comparison between the chars in the neighboring strings at the same indexes (i.e. first with first, second with second)
// if comparison passes, then it is 1, so dif_count (which counts the differences) increments, otherwise it doesn't increment
dif_count += val != str2[ind];
})
return dif_count;
}
// create array of zeros with the length of arr.length
checks = Array(arr.length).fill(0);
// below we compare each element with every another element.
//If there's a pair of strings str1 and str2 with the difference of 1 character, we set the corresponding indexes in "checks" array to 1.
//If the "checks" array contains all 1's then all the strings have pairs, otherwise test fails.
//If array contains duplicates, then test fails
dupes = 0;
arr.map((str1, ind1) => {
arr.map((str2, ind2) => {
if(difCount(str1, str2) == 1){
checks[ind1] = 1;
checks[ind2] = 1;
}
if(str1 == str2 && ind1 != ind2) dupes = 1;
})
})
// So, if there're no dupes and no zeros in the checks array, then the test has passed
pass = !dupes && !checks.includes(0) ? "pass" : "fail";
console.log(pass)