Last active
March 5, 2019 13:41
-
-
Save iuliaL/0849cefe46b41b45a732f0fadd492ed6 to your computer and use it in GitHub Desktop.
Find all substrings containing just unique values of a given length from a given string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example: "kjzskjkjk" 3 => [ "kjz", "jzs", "zsk", "skj" ] | |
function justUniqueVals(arr) { | |
return arr.filter((item, index, self) => self.indexOf(item) == index); | |
// not performant for long arrays!!! use occurences hashmap instead | |
} | |
function hasUniqueVals(arr) { | |
const filtered = justUniqueVals(arr); | |
return filtered.length == arr.length; | |
} | |
function substrings(string, num) { | |
const result = []; | |
if (string.length < num || | |
string.length == 0 || | |
(string.length == num && !hasUniqueVals) | |
) { | |
return result; | |
} | |
const input = string.split(""); | |
input.forEach((letter, index) => { | |
const substring = input.slice(index, index + num); | |
if (substring.length == num && hasUniqueVals(substring)) { | |
result.push(substring); | |
} | |
}); | |
return justUniqueVals(result).sort(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment