This method meticulously generates all possible prefixes for each string, subsequently comparing these to identify the longest common prefix across the set. It leverages a double iteration process to first gather all prefixes and then to iteratively compare these across strings, gradually narrowing down to the longest shared prefix. This approach, while straightforward, is less efficient for large datasets due to its exhaustive comparison mechanism.
Optimized Longest Common Prefix:
Enhancing efficiency, this optimized approach identifies the shortest string in the array as the potential longest common prefix, given that the common prefix cannot be longer than the shortest string. It then iterates through each character of this shortest string, comparing it with corresponding characters in other strings. Upon encountering a mismatch, it immediately returns the common prefix found up to that point. This method significantly reduces the number of comparisons, making it a superior solution for larger datasets.
1let strs = ['flower', 'flow', 'flight'];
23const prefixGnerator = (str) => {
4let elem = [];
5for (let i = 0; i < str.length; i++) {
6 elem.push(str.substring(0, i + 1));
7 }
8return elem;
9};
1011let longestCommonPrefix = function (strs) {
12if (strs.length === 0) return'';
13let elem = [];
14for (let i = 0; i < strs.length; i++) {
15 elem.push(prefixGnerator(strs[i]));
16 }
17let smallest = Infinity;
18for (let i = 0; i < strs.length; i++) {
19if (elem[i].length < smallest) {
20 smallest = elem[i].length;
21 }
22 }
2324let j = 0;
25let commonPrefix = [];
2627while (j < smallest) {
28let i = 0;
29let flag = true;
30while (i < elem.length - 1) {
31if (elem[i][j] !== elem[i + 1][j]) {
32 flag = false;
33 }
34 i++;
35 }
36if (flag) {
37 commonPrefix.push(elem[i - 1][j]);
38 }
3940 j++;
41 }
42return commonPrefix[commonPrefix.length - 1];
43};
4445const longestCommonPrefixOptimized = function (strs) {
46if (strs.length === 0) return'';
47let shortest = strs[0];
48for (let str of strs) {
49if (str.length < shortest.length) {
50 shortest = str;
51 }
52 }
53for (let i = 0; i < shortest.length; i++) {
54for (let str of strs) {
55if (str[i] !== shortest[i]) {
56return shortest.substring(0, i);
57 }
58 }
59 }
60return shortest;
61};
6263//TC : O(m * n^2)64console.log(longestCommonPrefix(strs));
65//TC : O(S), where S is the sum of all characters in all strings66console.log(longestCommonPrefixOptimized(strs));
67