Leetcode Longest Common Prefix
Fast strings in Javascript
It is important to note that something as simple as assigning a string to a variable will cost the length of the string in complexity a = &quot;12345&quot; will cost 5 characters. Assign to another variable and the cost is the same b = a will cost 5.
Every time you assign a string you need to count the length of that string. If you copy an array of strings then you move all the characters, not just the number of strings in the array.
You do a lot of string assignments in your code.
Avoid string assignment
The trick to handling strings is to avoid assigning strings if you can. Arrays and string array character referencing (eg a = &quot;abcdef&quot;; b = a[1])  lets you treat the JS string like a C (char *) string. You dont copy the string, you are just indexing into the string.
The only time any sequence of characters are copied is on the return. The performance increase is very significant.
const longestCommonPrefix = words =&gt; {
    var i, pos = 0, len = words.length;
    const char = words[0][pos];
    var min = words[0].length;
    for (i = 1; i &lt; len; i++) { // finds the min word length and check first char
        min = words[i].length &lt; min ? words[i].length : min;
        if (char !== words[i][pos] || pos === min) { return &quot;&quot; }
    }    
    pos ++;
    while (pos &lt; min) {  // check up to min word length.
        const char = words[0][pos];
        for (i = 1; i &lt;len; i++) {
            if (char !== words[i][pos]) { return words[0].substring(0,pos) }
        }
        pos ++;
    }
    return words[0].substring(0,pos);
}