LeetCode – Longest Common Prefix (Java)

Problem

Write a function to find the longest common prefix string amongst an array of strings.

Analysis

To solve this problem, we need to find the two loop conditions. One is the length of the shortest string. The other is iteration over every element of the string array.

Java Solution

public String longestCommonPrefix(String[] strs) {
    if(strs==null || strs.length==0){
        return "";
    }
 
    if(strs.length==1) 
        return strs[0];
 
    int minLen = strs.length+1;
 
    for(String str: strs){
        if(minLen > str.length()){
            minLen = str.length();
        }
    }
 
    for(int i=0; i<minLen; i++){
        for(int j=0; j<strs.length-1; j++){
            String s1 = strs[j];
            String s2 = strs[j+1];
            if(s1.charAt(i)!=s2.charAt(i)){
                return s1.substring(0, i);
            }
        }
    }
 
    return strs[0].substring(0, minLen);
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • SA

    hear hear! Is this a bug in the solution, or are Abhishek and I missing something simple?

  • TheForceAwakens

    Fails if the number of strings is less than the length of the smallest string.
    Setting minLen = Integer.MAX_VALUE works just fine.

  • Rudolf Eremyan

    I have modified last part of method, I think now method became more understandable

    public static String longestCommonPrefix(String[] strs) {
    if(strs==null || strs.length==0)
    return “”;

    if(strs.length==1)
    return strs[0];

    String minString = strs[0];
    for(String str : strs)
    if(str.length() = 0; i–){
    if(str.charAt(i) != minString.charAt(i))
    minString = minString.substring(0, i);
    }
    }

    return minString;
    }

  • Mike


    public static String findLongestCommonPrefix(String... values) {
    String s1 = values[0];
    for(int i=0; i<s1.length(); i++){
    for(int j=1; j= word.length() || word.charAt(i)!=s1.charAt(i)){
    return s1.substring(0,i);
    }
    }
    }
    return s1;
    }

  • Juan Melo

    my code in Java:

    public static String findLongestCommonPrefix(String... values) {
    if (values == null) {
    return null;
    }
    //find shortest string
    int shortestIndex = 0, len = Integer.MAX_VALUE;
    for (int i = 0; i < values.length; i++) {
    if (values[i].length() < len) {
    len = values[i].length();
    shortestIndex = i;
    }
    }
    //iterate thru shortest string and try to find prefixes in the rest of the array
    for (int i = 0; i 0) {
    newLength--;
    len = newLength;
    }
    }
    return values[shortestIndex].substring(0, len);

    }

    @Test
    public void testFindLongestCommonPrefix() throws Exception {
    assertEquals("Hell",LongestCommonPrefix.findLongestCommonPrefix("Hello", "HelloMan", "Hellio", "Hellan","Hellooooou"));
    assertEquals("Mont",LongestCommonPrefix.findLongestCommonPrefix("Monterrey", "MonteOlivos", "Montgomery", "Montreal","Montar"));
    }

  • b

    Scala:

    def findCommonPrefix[T](values: Seq[Seq[T]]): Seq[T] = {

    if (values.isEmpty) Seq.empty[T]

    else if (values.length == 1) values.head

    else {

    values.tail.foldLeft(values.head) {

    case (prev, next) =>

    var prefix = Seq.empty[T]

    next.takeWhile { v =>

    prefix :+= v

    prev.startsWith(prefix)

    }

    }

    }

    }

  • Rishabh Sanghvi

    public class LongestCommonPrefix {

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    String[] input = {“Hello”, “HelloMan”, “Hell”, “Hellan”};

    String result = getLongestCommonPrefix(input);

    System.out.println(“Result is ” + result);

    }

    public static String getLongestCommonPrefix(String[] input) {

    int minimumLength = Integer.MAX_VALUE;

    for(String str : input) {

    if (str.length() < minimumLength) {

    minimumLength = str.length();

    }

    }

    char[] charList = new char[minimumLength];

    for (int i = 0; i<minimumLength ; i++) {

    Character c = input[0].charAt(i);

    for(String str : input) {

    if (str.charAt(i) == c) {

    c = str.charAt(i);

    } else {

    return (new String(charList));

    }

    }

    if (c != null) {

    charList[i] = c;

    }

    }

    return (new String(charList));

    }

    }

  • CRH


    public String getLongestPrefix(ArrayList input){

    if(input==null || input.size()==0) return null;

    int minlen = Integer.MAX_VALUE;

    String shortest = null;

    // O(n) time complexity

    for(String s : input){

    if(s.length() < minlen) {

    minlen = s.length();

    shortest = s;

    }

    }

    int stop = shortest.length();

    for(int i=0;i<shortest.length();i++){

    char ch = shortest.charAt(i);

    for(String s : input){

    if(s.charAt(i) != ch){

    stop = i;

    break;

    }

    }

    }

    return shortest.substring(0,stop);

    }

  • Shannon McNeill

    I vote for a Ternary tree. Minimizes space.

    class TernaryNode {
    char data;
    boolean endOfWord;
    TernaryNode low;
    TernaryNode equal;

  • BobTheSCV

    You can solve this using a Trie as well I think. This is a very back-of-the-envelope solution sketch that probably contains a bug or two:

    interface TrieNode {
    int countChildren();
    TrieNode put(char c);
    }

    String longestSubstring(String[] strs) {
    if (strs.length == 0) {
    return “”;
    }

    int maxLen = Integer.MAX_VALUE;
    TrieNode root = new TrieNode();

    for (String str : strs) {
    TrieNode n = root;

    for (int i = 0; i < str.length() && i 1) {
    maxLen = Math.min(maxLen, i);
    break;
    }
    n = n.put(c);
    }
    }

    return strs[0].substring(0, Math.min(strs[0].length(), maxLen));
    }