JavaScript Algorithm: Two Strings

Max N
Level Up Coding
Published in
3 min readMar 3, 2020

--

For today’s algorithm, we are going to write a function called twoStrings that will take two strings, s1 and s2 as inputs.

You are given two strings and the goal of the function is to determine if both strings share a common substring. The substring can be as little as one character. If both strings have at least one character in common, the function will return YES. If both strings don’t share a common substring, the function will return NO.

Here is an example:

let s1 = "apple";
let s2 = "park";

If we look at the two strings especially the bold characters we see that both strings have the substrings, a and p in common. The function will return YES.

For this example:

let s1 = "pork";
let s2 = "wait";

For the two strings above, neither of them have any substrings in common so the function will return NO.

Let’s turn this into code:

let shortStr;
let longStr;

We create two variables, shortStr and longStr. The purpose of these two variables is to assign the longer of the two string inputs to the longStr variable and the shorter string to the shortStr variable. How do we know which string is shorter or longer than the other?

if(s1.length < s2.length){
shortStr = s1;
longStr = s2;
}else{
shortStr = s2;
longStr = s1;
}

In our if-statement, we check to see if s1 is shorter than s2. If it is, s1 is assigned to theshortStr variable and s2 to the longStr variable. If not, we switch variable assignments so that s2 is assigned to the shortStr variable and s1 to the longStr variable. If both strings happen to be the same length, the variable assignments within the else block are used by default.

We do this so that we can loop through the shortest string and see if any character exists within the longStr variable. It saves time. I’m sure there are way more efficient ways to do this but this one way.

for(let i = 0; i < shortStr.length; i++){
if(longStr.indexOf(shortStr[i]) !== -1){
return "YES";
}
}

In our for-loop, we loop through the characters of our shortStr variable. We use the indexOf()

--

--

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.