I need to find the substrings within my array. If I have an array: ["abc", "abcd", "abcde", "xyz"]
, my method should return the array members: abc
, abcd
, abcde
as each is a substring or a superstring of the other, but it should exclude "xyz" as it is not related to other strings in any way.
function find_substrings(arr) { var res = []; for (var i=0; i<arr.length; i++) { for (var j=0; j<arr.length; j++) { if (i !== j && (arr[i].indexOf(arr[j]) > -1 || arr[j].indexOf(arr[i]) > -1)) { res.push(arr[i]); break; } } } return res; } var arr = ["abc", "abcd", "abcde", "xyz"]; console.log(find_substrings(arr));
Here my code is of \$O(n^2)\$ complexity, as it's iterating twice over the complete array. Is there any optimal solution?
['abc', 'abcd', 'abcde', 'xyz', 'wxyz', 'vwxyz']
?\$\endgroup\$