Runtime error on leetcode

Over the last couple of weeks I have been solving some of the challenges on For one of the challenges (#14), I thought my solution would solve the problem, but I get a run-time error. Here is my code in replit which seems to work, but when I try to run the code (not submit) with my test data, I get a runtime error. It does not say what the error is, but maybe my solution is timing out? I thought maybe leetcode did not allow arrow functions, so I changed my code to using normal function syntax, but still can not get pass the runtime error. Can anyone tell me why I might be getting a runtime error?


I don’t see any runtime error (at least for this particular input). Is there an input that gives that error?

The console’s output is as expected, at least from the REPL you posted.

I figured out the runtime error was because my solution was unable to process the test case where the array was empty, so I had to adjust for that situation. Even after fixing that, I found my logic was incorrect. I went to sleep frustrated with my solution and when I woke up this morning, I had a thought of how best to solve it. Below is the solution which passed all the tests. After I solved it, I looked at a couple other solutions which were more efficient, so I may go back and try to optimize later.

var longestCommonPrefix = function(strs) {
    if (!strs.length) return '';
    for (var chars = strs[0], currSubstr='', i=0; i<chars.length;i++) {
      currSubstr += chars[i];
      for (j=1; j<strs.length;j++)
        if (currSubstr[i] !== strs[j][i]) { return currSubstr.substr(0,i); }
    return currSubstr;
1 Like