Skip to content

Instantly share code, notes, and snippets.

@iuliaL
Last active March 5, 2019 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iuliaL/0849cefe46b41b45a732f0fadd492ed6 to your computer and use it in GitHub Desktop.
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
// 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