Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find all substrings containing just unique values of a given length from a given string
// 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
You can’t perform that action at this time.