This is driving me insane, because I feel like it shouldn’t be a problem for me, and yet, here I am hoping one of you will take mercy on me. This function takes an array of strings and returns the longest common prefix. It seems to do that fine. The problem is that I want it to return null if there is no common prefix. Instead it returns nothing. With this particular input, it’s comparing the first letter in all words from index 1 onward to the first letter in the word at index 0. It gets to sunflower, sees that f !== s, but instead of returning null, I get nothing at all. What am I missing?
function prefix(words) {
for (let i = 0; i < words[0].length; i++) {
const char = words[0][i];
for (let j = 1; j < words.length; j++) {
if (i === words[j].length || words[j][i] !== char) {
return words[0].substring(0, i);
}
}
}
// No common prefix found
return null;
}
console.log(prefix(["flower", "flowers", "floyd", "flow", "sunflower", "floor"]))
4
Answers
Here’s what’s happening
In the case of
["flower", "flowers", "floyd", "flow", "sunflower", "floor"]
, the loop iterates through the characters of the first word and compares them to the other words.When
i
reaches the length of the first word (i = 5), there is no exit condition for the outer loop, so it continues to the next iteration.However, there’s no corresponding character in the other words, so the inner loop conditions
(i === words[j].length || words[j][i] !== char)
are not met.Since the loop completes without returning anything and all the words are not the same, the function ends without a return statement.
In JavaScript, when a function doesn’t return anything, it returns
undefined
, and that’s why you see nothing printed.The fix for this is to add a return statement after the outer loop to handle the case where the loop completes without finding a common prefix.
In your iterations for i=0 and j=4, Your code is comparing ‘s’ and ‘f’ — which will give true for your if condition, but in that case you are returning substring(0,0) for that word which gives an empty string (”) and hence you are returning empty string and not null- so not seeing any thing in your output.
Hope this helps, any feedback is welcome.
I solved the problem in a different manner.
// No common prefix found
return longestCommonPrefix ? longestCommonPrefix : null;
}
console.log(prefix(["flower", "flowers", "floyd", "flow", "sunflower", "floor"]))
You could check if the first character is not equal and in this case return null (or undefined):
You could simplify the code a bit and return null if there’s no more than one iteration to check the prefix:
And a benchmark: