14. Longest Common Prefix(Solution || Leetcode easy || Java)

Palakkgoyal
2 min readNov 27, 2022

--

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

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

SOLUTION(1):

Non-optimized

class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs[0].equals("")){
return "";
}

String prefix = strs[0];

for(int i = 1; i < strs.length; i++){

if(strs[i].equals("") || strs[i].charAt(0) != prefix.charAt(0)){
return "";
}

if(strs[i].length() < prefix.length()){

boolean temp = true;

for(int j = 0; j < strs[i].length(); j++){
if(strs[i].charAt(j) != prefix.charAt(j)){
prefix = prefix.substring(0,j);
temp = false;
break;
}
}
if(temp){
prefix = strs[i];
}
}
else{
for(int j = 0; j < prefix.length(); j++){
if(strs[i].charAt(j) != prefix.charAt(j)){
prefix = prefix.substring(0,j);
break;
}
}
}
}

return prefix;
}
}

SOLUTION(2):

Optimized

class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs[0].equals("")){
return "";
}

String prefix = strs[0];

for(int i = 1; i < strs.length; i++){

//if we do not find prefix at the starting of the string then we
//are going to decrease the size of prefix
while(strs[i].indexOf(prefix) != 0){
prefix = prefix.substring(0,prefix.length() -1);
}
}

return prefix;
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Longest Common Prefix.

Memory Usage: 40.4 MB, less than 89.19% of Java online submissions for Longest Common Prefix.

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet