Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Last active May 9, 2022 21:56
Show Gist options
  • Select an option

  • Save leonidkuznetsov18/1654f32ef1b30fc0ac6f058526f83c24 to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/1654f32ef1b30fc0ac6f058526f83c24 to your computer and use it in GitHub Desktop.
smallest substring of N that contains all the characters in K
// We have an array of strings stored in strArr, which will contain only two strings,
// the first parameter being the string N and the second parameter being a string K of some characters.
// Your goal is to determine the smallest substring of N that contains all the characters in K.
// For example: if strArr is ["aabdccdbcacd", "aad"] then the smallest substring of N that contains
// all of the characters in K is "aabd" which is located at the beginning of the string.
// Both parameters will be strings ranging in length from 1 to 50 characters and
// all of K's characters will exist somewhere in the string N. Both strings will only
// contain lowercase alphabetic characters.
// Examples
// Input: ["ahffaksfajeeubsne", "jefaa"] Output: aksfaje
// Input: ["aaffhkksemckelloe", "fhea"] Output: affhkkse
const input1 = ["aabdccdbcacd", "aaad"]; // "aabdccdbca"
const input2 = ["aabdccdbcacd", "aad"]; // "aabd"
const input3 = ["aaffhkksemckelloe", "fhea"] // "affhkkse"
const input4 = ["ahffaksfajeeubsne", "jefaa"] // "aksfaje"
const subIncludesAll = (str1, str2) => {
for (let i = 0; i < str1.length; i++) {
if (str2.indexOf(str1[i]) !== -1) {
str2 = str2.replace(str1[i], '');
};
};
return (str2.length === 0);
};
const smallestSubString = (input) => {
const str1 = input[0];
const str2 = input[1];
let shortStr = null;
for (let i = 0; i < str1.length; i++) {
for (let j = i; j < str1.length; j++) {
let testStr = str1.substr(i, j-i+1);
if (subIncludesAll(testStr, str2)) {
if (shortStr === null || testStr.length < shortStr.length) {
shortStr = testStr;
}
}
}
}
return shortStr;
};
console.log('----------')
console.log('Output: ', smallestSubString(input4))
console.log('----------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment