LeetCode problem #14 — Longest common prefix(JavaScript)
In this LeetCode challenge, we’re given a series of strings, and asked to find the longest common prefix amongst them.
For reference, the longest common prefix means the longest series of characters that are at the start of every string. For example, the longest common prefix in the words “had”, “hat” and “harp” is “ha”, whilst the longest common prefix in “only”, “one” and “out” is “o”.
Solution #1: Double loop
In this solution, we initially loop through the first provided string’s characters. For each character, we then loop through the remaining words, checking whether they contain the same character, in the same position.
If we find one that doesn’t, that means that the previous character tested marked the end of the longest prefix, so we return the first string up to and including that character. Otherwise, if our loops make it all the way to the end, that means the entire first string was found in all other strings, and thus that the entire first string is the longest prefix.
Note: I did originally use a combination of string1.indexOf(string2) === 0
and string1.substring(0, string2.length) === string2
for these comparisons, but then realised that comparing by 1 character each time made more sense, and was less CPU intensive.
Solution #2: Array.every()
Using the wonderful JavaScript array function every()
(which returns whether or not every element in an array passes a given condition), we can remove the (visible) second loop and tidy up our code a little. But to be honest, it’s otherwise a near-identical solution (except for the fact that unlike with the double-loop approach, this one also checks the initial string, which is technically a pointless comparison as that’s where we started):
Note: Although I used every()
, you can also use some()
with an inverted comparison to get the same result (in other words, “if some elements don’t contain this character” is the same as saying “if not every element contains this character”).