My java solution time complexity: O(nlogn) space complexity : O(1)


  • 0
        public String longestCommonPrefix(String[] strs) {
            if(strs.length == 1){
                return strs[0];
            }
            Arrays.sort(strs);
            int index = 0;
            while(strs.length >1 && index < strs[0].length() && index < strs[strs.length-1].length() 
                  && strs[0].charAt(index) == strs[strs.length -1].charAt(index)){
                index++;
            }
            return index > 0? strs[0].substring(0, index) :"";
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.