DEV Community

Cover image for Using JavaScript To Compare Two Strings Containing Deleting Element(s) – Two Versions
DavidNNussbaum
DavidNNussbaum

Posted on

Using JavaScript To Compare Two Strings Containing Deleting Element(s) – Two Versions

There are always several ways to code a solution and an example of this will be shown here. One is presented with two strings to be compared and the program should yield “true” if they match and “false” if they don’t. These strings can contain one or more of the symbol “$”. Each “$” deletes in turn its preceding letter. The comparison of the strings should take this into consideration.

In order to take Big O time consideration into account, “const” (the faster option) is used instead of “let”. Since the loops are not nested, we have O(n) instead of O(n^2).

The beginning is the same for both versions. A variable compareStrings is created which represents a function that takes in 2 parameters. We first eliminate the simplest case so if the strings match as they are then the return is “true”. If not, then 2 new empty arrays are created.

VERSION 1 CONTINUATION:

The letter “i” represents the index for the first argument and the string is iterated over. If the symbol “$” appears, then the last letter entered in the array is removed. If the item at that index is a letter, then it is added to the array. The same is done for the second argument except that the letter "j" is utilized. The arrays are then converted into strings and compared. If they are equivalent then ‘true” is returned, otherwise the return is “false”.

Image description

VERSION 2 CONTINUATION:

A variable loopLength is created and Math.max() is used to determine which argument’s length is longer. This is the number that the “i” which is the letter representing the index to iterate over the strings must be less than to ensure that even the longer string is completely iterated over. For each string it is first determined that the string is not undefined. If it is not then if the symbol “$” appears, then the last letter entered in the array is removed. If the item at that index is a letter, then it is added to the array. The same is done for the second argument. The arrays are then converted to strings and compared utilizing a ternary operator. If they are equivalent then ‘true” is returned, otherwise the return is “false”.

Image description

Please note that since “$” is eliminated, if that symbol appears at the beginning meaning that there were no letters to pop from the array, it will not change the “true” or “false” response.

Thanks for reading!

Top comments (0)