Algorithm to find prefix of elements in an array

Algorithm to find prefix of elements in an array

1 Like

Can you please elaborate the question?

I think your question relate to common prefix of elements in an array. If this is the question then solution is as follows: >

    function commonPrefix(strings){
       if(strings.length === 0){
           return "Invalid input";
       }
        
       let sortedstrings = strings.concat().sort();
       let str1 = sortedstrings[0];
       let str2 = sortedstrings[sortedstrings.length-1];
       let a = 0;
        
       while(a < str1.length && str1.charAt(a) === str2.charAt(a)){
           a++;
       }

       return str1.substring(0, a);
    }

Example:-
commonPrefix(["flower","flow","flight"]);
This will return fl

Time Complexity = O(n(logn))
Space Complexity = O(n)