# 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 i=0; while(true){ boolean flag = true; for(int j=1; j<strs.length; j++){ if(strs[j].length()<=i || strs[j-1].length() <=i || strs[j].charAt(i) != strs[j-1].charAt(i)){ flag = false; break; } }   if(flag){ i++; }else{ break; } }   return strs[0].substring(0, i); }```
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>
```
• Satish

``` { String[] s ={"arnan", "arp", "aril","a"}; int pos=0; String common = ""; for(int i=1;i<s.length;i++) { pos=0;```

``` if(!(common!=""&&s[i].startsWith(common))) { while(pos<=s[0].length()) { if(s[i].startsWith(s[0].substring(0, pos))) { common = s[0].substring(0, pos); } pos++; ```

```} } } System.out.println(common); } ```

• Rahul Jain

thanks !!

• Narendra

Thanks mate!!!!

• Bukary Kandeh

Java solution with only 2 Loops:
https://ide.geeksforgeeks.org/bPPk02NKd2

• Bukary Kandeh

``` Java solution with only 2 Loops:```

``` public static String LongestCommonPrefix(String[] str){ String prefix = ""; int min = str[0].length(); ```

``` for(int i=0; i<min; i++){ for(int j=1; j<str.length; j++){ if(str[0].charAt(i) != str[j].charAt(i)){ return prefix; } min = Math.min(min, str[j].length()); } prefix += str[0].charAt(i); } return prefix; } ```

• Vasubabu

public static String longestCommonPrefix(String[] strs) {
TreeMap trieMap = new TreeMap();

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

int minLength = strs[strs.length – 1].length();

for (int i = 0; i strs[i].length()) {
minLength = strs[i].length();
}
}

for (int i = 0; i < strs.length – 1; i++) {
for (int j = 0; j < strs.length – 1; j++) {
trieMap.putAll(findCommon(strs[j], strs[j + 1], minLength));
}
}

return trieMap.get(trieMap.firstKey());

}

private static TreeMap findCommon(String str1, String str2, int minLength) {
TreeMap tempMap = new TreeMap();

for (int i = 0; i < minLength; i++) {
if ((str1.charAt(i) != str2.charAt(i)) || (str1.length() == i+1 || str2.length() == i+1)) {
if ((str1.length() == i+1 || str2.length() == i+1)) {
tempMap.put(str1.substring(0, i+1).length(), str1.substring(0, i+1));
} else {
tempMap.put(str1.substring(0, i).length(), str1.substring(0, i));
}
return tempMap;
}
}
return tempMap;
}

• FooBarBaz

If the string we pick (0) is not the shortest, the if condition will break the loops. If it is the longest prefix (exactly), then we’ll return as normal:

``` public String longestCommonPrefix(String[] strs) { StringBuilder sb = new StringBuilder();```

``` if(strs == null || strs.length == 0) return sb.toString(); if(strs.length == 1) return strs[0]; int idx = 0; while(idx = s.length() || s.charAt(idx) != c) { //System.out.println(idx + " " + s.charAt(idx) + " " + c); return sb.toString(); } // end if } // end for sb.append(strs[0].substring(idx,idx + 1)); idx++; } //end while return sb.toString(); } // end longestCommonPrefix ```

• 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 {

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));
}