Strings Rearrangement

Description


Given an array of equal-length strings, check if it is possible to rearrange the strings in such a way that after the rearrangement the strings at consecutive positions would differ by exactly one character.

Example

  • For inputArray = ["aba", "bbb", "bab"], the output should be stringsRearrangement(inputArray) = false;

All rearrangements don’t satisfy the description condition.

  • For inputArray = ["ab", "bb", "aa"], the output should be stringsRearrangement(inputArray) = true.

Strings can be rearranged in the following way: "aa", "ab", "bb".

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.string inputArray

A non-empty array of strings of lowercase letters.

Guaranteed constraints: 2 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 15.

  • [output] boolean

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function stringsRearrangement(inputArray) {
    var ret = false;
    var solution = [];
    
    function bt () {
        for (var i = 0; i<inputArray.length; i++) {
            if(ret) break;
            solution.push(inputArray.splice(i,1)[0]);
            if (inputArray.length === 0) {
                ret = ret || checkSolution();
            }
            else{
                bt();
            }
            inputArray.splice(i,0,solution.pop());
        }
        
    }
    function checkSolution () {
        for (var i = 0; i < solution.length - 1; i++){
            var diff =0;
            for (var j = 0; j<solution[i].length; j++) {
                if (solution[i][j] !== solution[i+1][j]){
                    diff++;
                }
            }
            if(diff !== 1){
                return false;
            }
        }
        return true;
    }
    bt();
    return ret;
}