Naga Vara Pradeep, Yendluri

Home | LinkedIn | GitHub

Longest Common Prefix

Given: Array of strings Output: Find the longest common prefix string amongst an array of strings

Intuition:Try to find the word with minimum length. Then iterate over the words in array and check if the letters in the minimum length word are present. Iterate till the end of length of minimum length word and end the loop when any other letter is found other than the letter in minimum length word.

Java Implementation

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int min_length = strs[0].length();
        for(String word: strs){
            if(word.length() < min_length){
                min_length = word.length();
            }
        }
        String prefix = "";
        outerloop:
        for(int i = 0; i < min_length; i++){
            for(int j = 0; j < strs.length-1; j++){
                if(strs[j].charAt(i)!=strs[j+1].charAt(i)){
                    break outerloop;
                }
            }
            prefix += String.valueOf(strs[0].charAt(i));
        }
        return prefix;
    }
}