Last active
September 9, 2021 13:09
-
-
Save sranka23/e87e1f6a32d3384357ac794ed87daf69 to your computer and use it in GitHub Desktop.
Compatible substrings - Two strings are compatible if one string of length "m" is made of of "m" consecutive characters in the second string of length "n" (m<=n).
This file contains 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
/* | |
Author: Shourya Ranka | |
Objective: Two strings are compatible if one string of length "m" is made of of "m" consecutive characters in the second string of length "n" (m<=n). | |
1. "facebook", "beo" // compatible - b,e,o are consecutive letters in 'facebook' though the order is different. | |
2. "facebook", "aco" // not compatible - a,c,o are not consective letters present in 'facebook' | |
*/ | |
const stringSorter = str => str.split('').sort().join(''); | |
const areStringsCompatible = (str1, str2) => { | |
if(!(str1 && str2)){ | |
return false; | |
} | |
let parentStr = str1.length >= str2.length ? str1 : str2; | |
let testStr = str1.length <= str2.length ? str1 : str2; | |
for(let i=0;i<parentStr.length;i++){ | |
let tmpStr = parentStr.substring(i, i + testStr.length); | |
if(stringSorter(tmpStr) == stringSorter(testStr)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
// Test 1: Checks whichever input string is smaller and determines compatibility | |
console.log(areStringsCompatible('facebook','beo')); | |
console.log(areStringsCompatible('beo', 'facebook')); | |
// Test 2: If strings are same length and have same characters | |
console.log(areStringsCompatible('facebook', 'abcefkoo')); | |
// Test 3: Returns false if strings are not compatible | |
console.log(areStringsCompatible("facebook", "aco")); | |
// Test 4: Returns false for invalid input | |
console.log(areStringsCompatible("facebook")); | |
console.log(areStringsCompatible()); | |
console.log(areStringsCompatible("","")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code Execution @ https://codepen.io/sranka2310/pen/poweENW